Dart Future.wait for multiple futures and get back results of different types

后端 未结 3 732
伪装坚强ぢ
伪装坚强ぢ 2021-01-18 18:03

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 foos = await downl         


        
相关标签:
3条回答
  • 2021-01-18 18:45

    Well, type T is a generic type

    You know your types, so you can work with them.

    If your are using a FutureBuilder, you can access the different results using this. (same order you put them in the Future.wait method)

    snapshot.data[0] // maybe type List<Foo>
    snapshot.data[1] // maybe type List<Bar>
    snapshot.data[2] // maybe type String
    
    0 讨论(0)
  • 2021-01-18 18:48

    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())(),
    ]);
    
    0 讨论(0)
  • 2021-01-18 19:10

    I think is not possible to do in a super nice fashion. All you can do is something like this:

    void main() async {
      List<List<dynamic>> result = await Future.wait<List<dynamic>>([
        getStringData(),
        getIntData(),
      ]);
    
      print(result[0]);
      print(result[1]);
    }
    
    Future<List<String>> getStringData() {
      return Future.value(["a", "b"]);
    }
    
    Future<List<int>> getIntData() {
      return Future.value([1, 2]);
    }
    
    0 讨论(0)
提交回复
热议问题