【问题标题】:How to nest Futures to wait for each other in initState如何在 initState 中嵌套 Futures 以相互等待
【发布时间】:2021-06-19 16:17:01
【问题描述】:
首先我需要获取一些 id => 其中一个返回的 id 又名:userId 用于获取 mailboxId => mailboxId 用于获取消息模型列表。
PS:每个调用都是独立的,因为这就是 API 的构建方式
@override
void initState() {
super.initState();
futureIds = fetchIds();
// start those two after fetchIds() finishes
futureMailboxId = fetchMailboxId(userId);
futureLanguage = fetchLanguage(userId);
// start this after fetchMailboxId(userId) finishes
futureMessages = fetchMessages(mailboxId);
}
【问题讨论】:
标签:
flutter
dart
async-await
future
【解决方案1】:
你不能直接在init statse 等待,但你可以使用didChangeDependencies() 函数,你可以在那里等待,所以我在下面提到
@override
Future <void> didChangeDependencies() async{
futureIds = await fetchIds();
// TODO: implement didChangeDependencies
super.didChangeDependencies();
}
【解决方案2】:
futureDetails:是 StatefulWidget 的 Future 属性
Globals:包含在整个应用程序中使用的静态属性
Message:是带有工厂方法的模型fromJson
@override
void initState() {
super.initState();
futureDetails = fetchIds().then((List<int> ids) => {
Globals.userId = ids[0];
Future.wait([
fetchLanguage(Globals.userId),
fetchMailboxId(Globals.userId)
]).then((List<dynamic> futureResult) => {
Globals.mailboxId = futureResult[1];
fetchMessages(Globals.mailboxId).then((Map<String, dynamic> messagesAsJson) => {
messagesAsJson.forEach((msgJson) => Globals.messages.add(Message.fromJson(msgJson)));
});
});
});
}
@override
Widget build(BuildContext context) {
return FutureBuilder<Widget>(
future: futureDetails,
builder: (BuildContext context, AsyncSnapshot<List<int>> snapshot) {
if (snapshot.hasData) {
// display data empty/filled
} else if (snapshot.hasError) {
// display error
} else {
// display loader
}
}
);
}