gpt4 book ai didi

dart - 如何完成 future ?

转载 作者:行者123 更新时间:2023-12-03 04:16:46 24 4
gpt4 key购买 nike

我正在搜索类似以下内容的内容,其中我从方法中返回一个对象,该对象可以等待,并从其原始函数完成:

Future<dynamic> customFunction() {
// The following class does not exist, but I am searching for a class that would fill that gap.
FutureWithCompletion future = FutureWithCompletion();
() async { // A callback that represents the usecase.
// some computation
future.completeWith('something');
}
return future;
}

/// This function accesses [customFunction].
/// It should print out "something" once the computation is done.
anotherFunction() async => print(await customFunction());

最佳答案

您需要使用Completer:

Future<String> method() {
final completer = Completer<String>();
Timer(Duration(seconds: 5), () => completer.complete('result'));
return completer.future;
}

关于dart - 如何完成 future ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52172731/

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