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.
// Function that replicates a slow operationFuture<void> getOrder(){Future.delayed(Duration(seconds: 2), () =>print("Vanilla Shot"));}void main() {getOrder();//Notice how the following appears on screen firstprint("Getting order...");}
A future is an instance of the Future class. It can have two states: uncompleted or completed.
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);}
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.
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
.
If unsuccessful, a future will return an error.
// Function that replicates an errorFuture<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.