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.dart file, in the _FuturePageState class:
Completer completer;
Future<int> getNumber() {
completer = Completer<int>();
calculate();
return completer.future;
}
calculate() async {
await new Future.delayed(const Duration(seconds : 5));
completer.complete(42);
}
- If you followed the previous recipes in the chapter, comment out the code in the onPressed function.
- Add the following code in the onPressed() function:
getNumber().then((value) {
setState(() {
result = value.toString();
});
});
If you try the app right now, you'll notice that after 5 seconds delay, the number 42 should show up on the screen.