The most obvious way to catch errors in a then() callback is using the catchError callback. To do so, follow these steps:
- Add the following method to the the _FuturePageState class in the main.dart file:
Future returnError() {
throw ('Something terrible happened!');
}
- Whenever a method calls returnError, an error will be thrown. To catch this error, place the following code in the onPressed method of the ElevatedButton:
returnError()
.then((value){
setState(() {
result = 'Success';
});
}).catchError((onError){
setState(() {
result = onError;
});
}).whenComplete(() => print('Complete'));
- Run the app and click the GO! button. You will see that the catchError callback was executed, updating the result State variable as shown in the following screenshot...