A future in Flutter is an object that represents the result of an asynchronous operation. It can be used to wait for the result of the operation, or to be notified when the result is available. Futures are used extensively in Flutter for tasks such as:
- Loading data from the network
- Performing long-running tasks in the background
- Waiting for user input
How to Use a Future in Flutter
To use a future in Flutter, you first need to create one. This can be done using the `Future` constructor, or by using one of the many methods that return futures, such as `http.get`.
Once you have created a future, you can use it in a number of ways. The most common way is to use the `then` method to specify a callback function to be called when the future completes. The callback function will be passed the result of the future as its argument.
For example, the following code uses the `http.get` method to fetch data from a URL and then uses the `then` method to specify a callback function to be called when the data is loaded:
```dart
Future<String> fetchAlbum() async {
final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/albums/1'));
if (response.statusCode == 200) {
// If the server returned a 200 OK response,
// then parse the JSON.
return Album.fromJson(jsonDecode(response.body));
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load album');
}
}
```
The `then` method can also be used to chain multiple futures together. For example, the following code uses the `then` method to chain together two futures: the first future fetches data from a URL, and the second future prints the data to the console:
```dart
Future<String> fetchAlbum() async {
final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/albums/1'));
if (response.statusCode == 200) {
// If the server returned a 200 OK response,
// then parse the JSON.
return Album.fromJson(jsonDecode(response.body));
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load album');
}
}
void printAlbum(Album album) {
print(album.title);
}
Future<void> main() async {
// Fetch the album from the network.
final album = await fetchAlbum();
// Print the album's title.
printAlbum(album);
}
```
Conclusion
Futures are a powerful tool for managing asynchronous operations in Flutter. They can be used to wait for the result of an operation, to be notified when the result is available, or to chain multiple futures together.
Tags:
future