从Future中返回值

时间:2019-05-13 11:44:05

标签: dart flutter

我们可以从dart中的Future对象返回值还是从中获取值。通过阅读文档,我可以理解我们可以在Future类的then方法中传递一个函数,但是我仍然不知道如何返回该值。

将以下内容视为伪代码

Int getTotalPay(){
Future<int> pension = getPensionFundAPI(); // a long running api call. don't wait here and call to next api
int salary = getTotalSalary();
//wait here till we get the int value received in Future when the above api call completes.
int result = salary + pension;
print(result);

返回结果;     }

我知道我可以打电话给Future.then,然后在其中传递一个回调方法。但是我的目的是要在那时之外返回结果。与我们在Java和其他oops语言中所做的一样。

有可能飞镖吗?

2 个答案:

答案 0 :(得分:0)

您可以使用await,但是您的方法需要async。 我认为您的方法将是这样的:

void main() async {
  int pension = await getPensionFundAPI(); // a long running api call. don't wait here and call to next api
  int salary = getTotalSalary();
  //wait here till we get the int value received in Future when the above api call completes.
  int result = salary + pension;
  print(result);
}

所以await将阻塞方法,直到返回值。

答案 1 :(得分:-1)

不可能。就像将您80岁的自我带到这里和现在一样:)

但是,您可以编写看起来像可能的代码,但实际上是在不同的时间运行单个函数的不同部分。为此,您需要了解async and await keywords