【问题标题】:Flutter, how to Future.wait numerous functions?Flutter,Future.wait如何实现众多功能?
【发布时间】:2021-08-20 04:15:28
【问题描述】:

我知道 Future.wait 是如何工作的

await Future.wait([
      functionA(),
      functionB()
    ]).then((data) {
     
    });

但我想知道的是

如果函数的数量不固定,调用的函数的数量根据情况而变化呢? (功能都一样)

【问题讨论】:

  • 您可以动态构建一个List<Future<T>> 以传递给Future. wait
  • @jamesdlin 你的意思是 Future.wait([ variable>]);?以及如何设置不同的参数??
  • 您可以随意调用函数,但将返回的Future 添加到List,然后您可以在列表中使用Future.wait

标签: flutter dart


【解决方案1】:

只要您有一个可迭代的引用,您就可以映射它并返回 Future 函数。

Future<void> main() async {
  final List<int> resultFromApi = <int>[1, 2, 3, 4, 5];
  final List<int> finalResult = await Future.wait(resultFromApi.map(
    (int data) => complexProcess(data), // return the Future
  ));
  
  print(finalResult);
}

Future<int> complexProcess(int data) async {
  await Future<void>.delayed(const Duration(seconds: 1));
  return data * 10;
}

【讨论】:

    【解决方案2】:

    详细说明我的 cmets,您可以动态构建 ListFutures 并在其上使用 Future.wait。例如:

    Future<void> doAsynchronousStuff() async {
      var waitList = <Future<void>>[];
      if (someCondition) {
        waitList.add(someAsynchronousFunction(someArgument));
      }
    
      if (someOtherCondition) {
        waitList.add(someOtherAsynchronousFunction(someOtherArgument));
      }
    
      // ... and so on...
    
      await Future.wait(waitList);
    }
    

    如果您需要处理来自异步函数的不同返回值,您可以使用设置局部变量的匿名函数。见Dart Future.wait for multiple futures and get back results of different types

    【讨论】:

      猜你喜欢
      • 2019-02-13
      • 2020-06-27
      • 1970-01-01
      • 2023-01-22
      • 1970-01-01
      • 2022-07-04
      • 2023-04-05
      • 1970-01-01
      • 2023-03-13
      相关资源
      最近更新 更多