What are Dart futures?

A future is a valuable construct that allows asynchronous programming in Dart. Asynchronous programming is programming that caters to delayed operations. These delayed operations happen when you need to fetch data over a server, write to a database, or read a file on the system (commonly referred to as I/O operations).

With asynchronous programming, you can tell your computer that it is free to perform other operations while the asynchronous operation completes.

svg viewer
// Function that replicates a slow operation
Future<void> getOrder(){
Future.delayed(
Duration(seconds: 2), () =>
print("Vanilla Shot"));
}
void main() {
getOrder();
//Notice how the following appears on screen first
print("Getting order...");
}

What is a future?

A future is an instance of the Future class. It can have two states: uncompleted or completed.

Uncompleted

When a future is called, but has not returned a value, the future is in the uncompleted state.

Future<String> getOrder(){
Future.delayed(
Duration(seconds: 2), ()
=> 'vanilla shot');
}
void main() {
var order = getOrder();
print("Getting order...");
print(order);
}

Completed

If the asynchronous call is successful, the future completes with a value. Otherwise, it completes with an error.

Future<String> getOrder(){
return Future.delayed(
Duration(seconds: 2), ()
=> 'vanilla shot');
}
void main() async {
var order = getOrder();
print("Getting order...");
print(await order);
}

Read more about getting a program to wait using async/await, here.

a. Completing with a value

If successful, a future of type Future<String> will return a String value. Similarly, Future<T> (a future with any valid type T) will return T.

b. Completing with an error

If unsuccessful, a future will return an error.

// Function that replicates an error
Future<void> getOrder(){
Future.delayed(
Duration(seconds: 2), ()
=> throw Exception('Some Error'));
}
void main() {
getOrder();
print("Getting order...");
}

Read more about asynchronous programming in Dart in the official documentation.

Copyright ©2024 Educative, Inc. All rights reserved