【发布时间】:2021-01-01 00:13:37
【问题描述】:
我找到了如何在构建小部件时等待 2 个不同的未来的答案,但它们属于同一类型。 Example from here:
但是如果firstFuture() 和secondFuture() 返回不同的值类型——例如int 和String(或我的用例中的不同类),是否也有可能? AsyncSnapshot<List<bool>> snapshot 中的 bool 对我来说是个挑战……
FutureBuilder(
future: Future.wait([
firstFuture(), // Future<bool> firstFuture() async {...}
secondFuture(),// Future<bool> secondFuture() async {...}
//... More futures
]),
builder: (
context,
// List of booleans(results of all futures above)
AsyncSnapshot<List<bool>> snapshot,
){
// Check hasData once for all futures.
if (!snapshot.hasData) {
return CircularProgressIndicator();
}
// Access first Future's data:
// snapshot.data[0]
// Access second Future's data:
// snapshot.data[1]
return Container();
}
);
我还发现了另一个 answer 具有不同的类型,但这适用于函数而不是类
List<Foo> foos;
List<Bar> bars;
List<FooBars> foobars;
await Future.wait<void>([
downloader.getFoos().then((result) => foos = result),
downloader.getBars().then((result) => bars = result),
downloader.getFooBars().then((result) => foobars = result),
]);
processData(foos, bars, foobars);
【问题讨论】: