Future

Future objects are representation of the result of an asynchronous operation that will be completed later on.

You can access the result of a Future by using the await keyword. But keep in mind that you can only use the await keyword in an asynchronous function which you declare by using the async keyword! You can specify the type of the returned value and if you do not return a concrete value you should specify the type as being void.

The Future object has very useful constructors. The default one takes an asynchronous function as an argument. The future will then complete when the function returns a value.

Future(() async {…});

Then you can use the delayed(Duration) constructor, the Future will complete after x time (depending on the duration you specified).

You also have the wait(Iterable<Future>) constructor which can be very useful if you want to run multiple requests at the same time and then do something after each one of your requests completed.

Then you can also just create an async function. This may be the simplest way of creating a Future object async () => Future object .

Because of that, you should never write void myFunc() async => ... but Future<void> myFunc() async => ... and if you return an actual value, write Future<String> myFunc() async => ... .

Other constructors can sometimes have certain usefulness!

Here is a complete example demonstrating how to use Future:

Awaiting the doARequest2 will not freeze the code but it will not produce any error because it does not return a Future object.

Now you may wonder, how can I catch an error caused by a Future? Well simply use a try catch as usual!

If you are building an app with Flutter, you can use the FutureBuilder widget which allows you to update the view whenever the state of the future changes. It can be very helpful in a situation where you want to display a loading widget until the future is completed.