我找到了如何在构建小部件时等待 2 个不同的 future 的答案,但它们属于同一类型。 Example from here:
但是如果firstFuture()
也有可能吗?和 secondFuture()
返回不同的值类型 - 例如 int 和 String (或我的用例中的不同类)? bool
在 AsyncSnapshot<List<bool>> snapshot
对我来说是个挑战……
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);
最佳答案
好吧,您可以随时使用 Object作为这两种方法的最低共同返回值:
Future.wait<Object>([firstFuture(), secondFuture()])
但是您必须转换结果 List<Object>
的条目。回到你认为应该的样子。不完美,但它会工作。就个人而言,我更喜欢你已经发现的方法,只返回最小的 future ,
Future<void>
并让它写入方法内的各个变量。这也不是完美的,但它保持了类型安全。
关于flutter - 当 future 返回不同的值类型时,Future.wait 可能在未来的构建器中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63881492/