如何完成未来?

问题描述 投票:0回答:2

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

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());
dart
2个回答
3
投票

你需要使用Completer

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

0
投票
return Future.value('something`);

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

© www.soinside.com 2019 - 2024. All rights reserved.