gpt4 book ai didi

flutter - Flutter:结合多个Future 任务

转载 作者:行者123 更新时间:2023-12-03 03:21:29 25 4
gpt4 key购买 nike

如何合并多个FutureTask,以便我们可以在同一响应中获得所有回调。
我们像这样使用Future<T>

Future<String> getData(int duration) async {
await Future.delayed(Duration(seconds: duration)); //Mock delay
return "This a test data for duration $duration";
}
调用上述方法,如 getData(2).then((value) => print(value));如果我们要调用多个“ future 任务”,我们该怎么做?

最佳答案

为此,FutureGroup可用于合并多个流

FutureGroup provides us the functionality of combining multiplefutures into one single group, which will give the callback at the endwhen all future tasks work gets completed.


依赖项:
dependencies:
async: ^2.4.1
如何实现FutureGroup?
FutureGroup futureGroup = FutureGroup();
futureGroup.add(future1);
futureGroup.add(future2);
futureGroup.add(future3);
使用:
void main()  {
Future<String> future1 = getData(2);
Future<String> future2 = getData(4);
Future<String> future3 = getData(6);
FutureGroup futureGroup = FutureGroup();
futureGroup.add(future1);
futureGroup.add(future2);
futureGroup.add(future3);
futureGroup.close();
futureGroup.future.then((value) => {print(value)});
}

Future<String> getData(int duration) async {
await Future.delayed(Duration(seconds: duration)); //Mock delay
return "This a test data";
}
输出:

I/flutter ( 5866): [This a test data, This a test data, This a testdata] // Called after 6 seconds.


注意:当所有“将来的任务”完成时,它将仅被调用一次,此处将在6秒钟后运行。

关于flutter - Flutter:结合多个Future <T>任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62731654/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com