首页 > 解决方案 > 当期货返回不同的值类型时,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);

标签: flutterfuture

解决方案


好吧,您始终可以使用Object作为这两种方法的最低公共返回值:

Future.wait<Object>([firstFuture(), secondFuture()])

但是您必须将结果的条目List<Object>转换回您认为它们应该是的状态。不完美,但它会工作。

就个人而言,我更喜欢你已经发现的方法,只返回最小的未来,aFuture<void>并让它写入方法内的相应变量。这也不是完美的,但它保持了类型安全。


推荐阅读