I want to do something after a lot of future function done,bu I do not know how to write the code in dart? the code like this:
for (var d in data) { d.loadData().then() } // when all loaded // do something here
but I don't want to wait them one by one:
for (var d in data) { await d.loadData(); // NOT NEED THIS }
how to write those code in dart?
A future (lower case “f”) is an instance of the Future (capitalized “F”) class. A future represents the result of an asynchronous operation, and can have two states: uncompleted or completed. Note: Uncompleted is a Dart term referring to the state of a future before it has produced a value.
wait<T> method Null safetyReturns a future which will complete once all the provided futures have completed, either with their results, or with an error if any of the provided futures fail.
What is the difference between async and async* in Dart? The difference between both is that async* will always return a Stream and offer some syntax sugar to emit a value through the yield keyword. async gives you a Future and async* gives you a Stream.
There are two different ways to execute a Future and utilize the value it returns. If it returns any whatsoever. The most well-known way is to await on the Future to return. For everything to fall into work, your function that is calling the code must be checked async.
You can use Future.wait
to wait for a list of futures:
import 'dart:async'; Future main() async { var data = []; var futures = <Future>[]; for (var d in data) { futures.add(d.loadData()); } await Future.wait(futures); }
DartPad example
Existing answer gives enough information, but I want to add a note/warning. As stated in the docs:
The value of the returned future will be a list of all the values that were produced in the order that the futures are provided by iterating futures.
So, that means that the example below will return 4
as the first element (index 0), and 2
as the second element (index 1).
import 'dart:async'; Future main() async { print('start'); List<int> li = await Future.wait<int>([ fetchLong(), // longer (which gives 4) is first fetchShort(), // shorter (which gives 2) is second ]); print('results: ${li[0]} ${li[1]}'); // results: 4 2 } Future<int> fetchShort() { return Future.delayed(Duration(seconds: 3), () { print('Short!'); return 2; }); } Future<int> fetchLong() { return Future.delayed(Duration(seconds: 5), () { print('Long!'); return 4; }); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With