flutter - 当期货返回不同的值类型时,Future.wait 可能在未来的构建器中?
问题描述
我找到了如何在构建小部件时等待 2 个不同的未来的答案,但它们属于同一类型。来自这里的示例:
但是是否也有可能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();
}
);
我还找到了另一个不同类型的答案,但这适用于函数而不是类
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>
转换回您认为它们应该是的状态。不完美,但它会工作。
就个人而言,我更喜欢你已经发现的方法,只返回最小的未来,aFuture<void>
并让它写入方法内的相应变量。这也不是完美的,但它保持了类型安全。
推荐阅读
- python - RegEx 用于重复出现的短语
- c# - C#全局注册鼠标点击
- haskell - 检查 Bool 的可除性总是导致错误
- python - 将 click.MultiCommand 与类方法一起使用
- php - 如何使用 Firebase 找到我的 android 设备 ID 以与 php 通知脚本一起使用?
- python - 将嵌套的 JSON 解析为 pandas DataFrames
- python-3.x - Pandas - 基于两个数据帧之间的公共列从另一个数据帧聚合列值
- javascript - 表悬停(引导程序)不适用于反应
- python-3.x - PyQt4 到 PyQt5,Beautiful Soup,内核死机,重启
- wordpress - Wordpress API - 如何以单数与复数自定义帖子类型响应显示不同的数据