Reputation: 43
I recently starting developing in flutter. When starting my app I first want to load Data from different sources. I am having trouble with this and it seems like I haven't understood async / await yet.
What I want to do
When starting my App I want to load Data from multiple Sources. This should be done parallel but should only continue once all data sources are fully loaded.
What I tried
import 'package:flutter/material.dart';
class AsyncTester extends StatefulWidget {
@override
_AsyncTesterState createState() => _AsyncTesterState();
}
class _AsyncTesterState extends State<AsyncTester> {
@override
void initState() {
super.initState();
startApplication();
}
@override
Widget build(BuildContext context) {
return Container();
}
void startApplication() async {
await loadData();
print("starting Application!");
}
loadData() {
loadDataSource1();
loadDataSource2();
}
void loadDataSource1() async {
await Future.delayed(Duration(seconds: 3));
print("Data Source 1 loaded.");
}
void loadDataSource2() async {
await Future.delayed(Duration(seconds: 2));
print("Data Source 2 loaded.");
}
}
The output is:
I/flutter (23100): starting Application!
I/flutter (23100): Data Source 2 loaded.
I/flutter (23100): Data Source 1 loaded.
I don't understand why startApplication() does not wait for loadData() to finish. I thought that is exactly what await does?
BTW I am nesting loadDataSource1() and loadDataSource2() in loadData() because doing this
void startApplication() async {
await loadDataSource1();
await loadDataSource2();
print("starting Application!");
}
would load the Data after one another. Is this correct or is there a better way to do this?
Upvotes: 3
Views: 2700
Reputation: 7308
You should use Future.wait
, this method will execute both of your asynchronous operation in parallel and will complete once they are all finished:
void startApplication() async {
await Future.wait([
loadDataSource1(),
loadDataSource2(),
]);
print("starting Application!");
}
Upvotes: 11