You can also call the completeError method of a Completer when you need to deal with an error:
- Change the code in the calculate() method like this:
calculate() async {
try {
await new Future.delayed(const Duration(seconds : 5));
completer.complete(42);
}
catch (_) {
completer.completeError(null);
}
}
- In the call to getNumber, you could then concatenate a catchError to the then function:
getNumber().then((value) {
setState(() {
result = value.toString();
});
}).catchError((e) {
result = 'An error occurred';
});