如何完成未来?

时间:2018-09-04 19:20:00

标签: dart

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

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

2 个答案:

答案 0 :(得分:3)

您需要使用Completer

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

答案 1 :(得分:0)

return Future.value('something`);

否则请使用Completer https://api.dartlang.org/stable/2.0.0/dart-async/Completer-class.html