Future.wait([future1(), future2(), future3()])
Run the 3 futures in parallel. It's better than:
await future1();
await future2();
await future3();
The following example explain the benefits of Future.wait([]):
Future<String> getValue1() {
return Future.delayed(Duration(seconds: 2),() => "value1");
}
Future<String> getValue() {
return Future.delayed(Duration(seconds: 2), () => "value2");
}
void main(List<String> arguments) async {
var stp = Stopwatch()..start();
await Future.wait([getValue(),getValue1()]);
stp.stop();
print("when you execute it with Future.wait: ${stp.elapsedMilliseconds}");
var stp2 = Stopwatch()..start();
await getValue1();
await getValue();
stp2.stop();
print("when you execute futures one after an other: ${stp2.elapsedMilliseconds}");
}
But as all the futures are running on the main thread. you cannot consider multithreading.
You can use isolates for better performance. In Dart/flutter, there's no multithreading like Java or c#, etc. Instead, we use isolates
. An Isolate
is something like a Thread but includes his own memories. The first isolate can't access the memories of the other isolate but those isolates can communicate using ports. To better understand you can check the links below:
explain everything with details
When, why, and how to multithread in Flutter
The boring show Ep 30
I wish that those resources help you.