Dart Future。等待多个期货并获得不同类型的结果 [英] Dart Future.wait for multiple futures and get back results of different types

查看:161
本文介绍了Dart Future。等待多个期货并获得不同类型的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Flutter从服务器下载3套不同的数据,然后对这3套数据全部进行处理。我可以这样做:

  List< Foo> foos =等待downloader.getFoos(); 
List< Bar>酒吧=等待downloader.getBars();
List< FooBars> foob​​ars =等待downloader.getFooBars();

processData(foos,bars,foobars);

但是我更愿意并行异步下载所有3个数据集 。我已经看到Dart具有此 Future.wait方法

  Future< List< T>>等待< T>(
Iterable< Future< T>>期货,{
bool eagerError:false,
void cleanUp(
T successValue

})

但是看起来这只会返回相同类型(T)的值。我有3种不同的类型,所以我不知道如何使用它来获取3个数据集。



实现此目标的最佳替代方法是什么?



谢谢!

解决方案

您需要调整每个 Future< T> s转换为 Future 的常见类型。您可以使用 Future< void>

  List< Foo> foos; 
List< Bar>酒吧;
List< FooBars> foob​​ars;

等待Future.wait< void>([
downloader.getFoos()。then((result)=> foos = result),
downloader.getBars()。 then((结果)=>条=结果),
downloader.getFooBars()。then((结果)=> foobars =结果),
]);

processData(foos,bars,foobars);

或者,如果您更喜欢 await 而不是 .then() Future.wait 的调用可以是:



< pre class = lang-dart prettyprint-override> await Future.wait< void>([
(()async => foos = await downloader.getFoos())(),
(()异步=>条=等待downloader.getBars())(),
(()异步=> foobars =等待downloader.getFooBars())(),
]);


I'm using Flutter to download 3 different sets of data from a server, then do something with all 3 sets. I could do this:

List<Foo> foos = await downloader.getFoos();
List<Bar> bars = await downloader.getBars();
List<FooBars> foobars = await downloader.getFooBars();

processData(foos, bars, foobars);

But I'd prefer to download all 3 data sets asynchronously in parallel. I've seen that Dart has this Future.wait method:

Future<List<T>> wait <T>(
   Iterable<Future<T>> futures, {
   bool eagerError: false, 
   void cleanUp(
      T successValue
   )
}) 

However it looks like this will only return values of the same type (T). I have 3 different types, so I don't see how I can use this and get my 3 data sets back.

What's the best alternative way to achieve this?

Thanks!

解决方案

You need to adapt each of your Future<T>s to a common type of Future. You could use Future<void>:

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);

Or if you prefer await to .then(), the Future.wait call could be:

await Future.wait<void>([
  (() async => foos = await downloader.getFoos())(),
  (() async => bars = await downloader.getBars())(),
  (() async => foobars = await downloader.getFooBars())(),
]);

这篇关于Dart Future。等待多个期货并获得不同类型的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆