我最近开始使用 flutter 进行开发。当启动我的应用程序时,我首先要加载来自不同来源的数据。我在这方面遇到了麻烦,似乎我还没有理解异步/等待。
我想做的事
启动我的应用程序时,我想从多个源加载数据。这应该并行完成,但只有在所有数据源完全加载后才应继续。
我尝试过的
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.");
}
}
Run Code Online (Sandbox Code Playgroud)
输出是:
I/flutter …