Completing Futures
Using a Future with then, catchError, async, and await is probably enough for most use cases, but there is another way to deal with asynchronous programming in Dart and Flutter: the Completer class.
Completer creates Future objects that you can complete later with a value or an error. We will be using Completer in this recipe.
Getting ready
In order to follow along with this recipe, there are the following requirements:
- You can modify the project completed in the previous recipes in this chapter.
- OR, you can create a new project from the starting code available at https://github.com/PacktPublishing/Flutter-Cookbook/tree/master/chapter_07.
How to do it...
In this recipe, you will see how to use the Completer class to perform a long-running task:
- Add the following code in the
main.dartfile, in the_FuturePageStateclass:
late Completer completer;
Future getNumber() {
completer = Completer<int>();
calculate();
return completer.future;
}
calculate...