Reputation: 6087
On Swift, we have try?
when the error handling is just little of importance, and we just want to silence the whole ordeal and just "give me null if it fails".
Is there such thing in Flutter? I tried to find it, but I can only find the usual try ... catch
clause on the documentation. I mean, sure I can make it like this:
dynamic result = null;
try { result = json.decode(response.body); } catch (e) { }
But I'm trying to find something more like this if it exists:
var result = try? json.decode(response.body);
This will have the added value of not having to manually type the variable type beforehand and let the lint/editor/compiler do that by simply using var
(though in this specific case the type result might be dynamic
).
Upvotes: 0
Views: 128
Reputation: 89965
There isn't a Dart language feature to do it. I'm not familiar with how try?
works in Swift, but one potential problem for such a construct in Dart is that without specifying what you catch, you could catch logical errors (such as failed assertions).
If you don't mind an extra level of function calls, you could write a function to make it (arguably) a bit more convenient (and this also would give you control over what to catch):
T? doOrDoNot<T>(T Function() closure) {
try {
return closure();
} on Exception {
return null;
}
}
var result = doOrDoNot(() => json.decode(response.body));
Upvotes: 1