【发布时间】:2021-06-22 19:02:44
【问题描述】:
我最近开始使用 Flutter 进行开发。 启动我的应用程序时,我首先想从不同来源加载数据。 我遇到了麻烦,似乎我还没有理解 async / await。
我想做的事
启动我的应用程序时,我想从多个来源加载数据。这应该并行完成,但只有在所有数据源完全加载后才能继续。
我尝试了什么
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.");
}
}
输出是:
I/flutter (23100):启动应用程序!
I/flutter (23100):已加载数据源 2。
I/flutter (23100):已加载数据源 1。
我不明白为什么 startApplication() 不等待 loadData() 完成。 我认为这正是 await 的作用?
顺便说一句,我将 loadDataSource1() 和 loadDataSource2() 嵌套在 loadData() 中,因为这样做
void startApplication() async {
await loadDataSource1();
await loadDataSource2();
print("starting Application!");
}
将一个接一个地加载数据。 这是正确的还是有更好的方法来做到这一点?
【问题讨论】:
-
在
loadData()函数中,您需要await进行其他调用,以暂停程序执行,直到返回具有值的Future
标签: flutter dart asynchronous async-await