⏲️ Future
Use a Future to handle a single async event
Create a Future
Many APIs in Dart/Flutter return Futures. To simulate an async event, we can create a future that will resolve after a 5 second delay.
futures.dart
var delay = Future.delayed(Duration(seconds: 5));
Handle a Future
A future can either be a success or a error. Use then then
to handle a successful resolution and catchError
to handle an error.
futures.dart
delay
.then((value) => print('I have been waiting'))
.catchError((err) => print(err));
Async Await Syntax
Async-await provides a cleaner (arguably) syntax for writing asynchronous code. The async
keyword tells Dart to return a Future, while await
pauses the execution of the function until the Future resolves.
futures.dart
Future<String> runInTheFuture() async {
var data = await Future.value('world');
return 'hello $data';
}