Dart 和 Flutter:需要帮助了解如何捕捉未来

Dart & Flutter: Need help understanding how to capture futures

我正在学习 Dart 语言的 Future 对象,并且一直在试验它们。我想创建一个包含未来对象的异步函数。 后者应该 return 一个字符串,函数应该 return 无论将来 return 是什么。 我知道我不太会说话,但这里是代码和注释:

Future<String> getData(int number) async { // here I created my async function
  // here is my future object assigned to a variable called thisFuture
  Future<String> thisFuture = await Future.delayed(Duration(seconds: 1), () {
    'this is a future string $number.';
  });
  // here, I am returning the future object
  return thisFuture;
}

main(){
// inside my main function, I want to assign the above function to a variable without executing it
Future<String>captureFunc = getData; // I get an error
print(captureFunc(01)).then((e)=> print(e)); // here I want to access the string inside the future object.
// I am expecting to get: this is a future string 01.
}

我遇到异常:

A value of type 'Future<String> Function(int)' can't be assigned to a variable of type 'Future<String>'.
This expression has a type of 'void' so its value can't be used.
The expression doesn't evaluate to a function, so it can't be invoked.

请帮助我了解 futures、函数内部的 futures 以及如何从包含 future 类型对象的函数中获取值。

错误是您试图将 returns 字符串传递给字符串的函数。而您在 getData 中的内在 Future 什么也没有返回。在 main() 中,您正在用 then 解决未来问题并尝试将其打印出来。试试下面的代码:

   Future<String> getData(int number) async { // here I created my async function
      // here is my future object assigned to a variable called thisFuture
      var thisFuture = await Future.delayed(Duration(seconds: 1), () {
        return 'this is a future string $number.';
      });
      // here, I am returning the future object
      return thisFuture;
    }
    
    main(){
    // inside my main function, I want to assign the above function to a variable without executing it
    var captureFunc = getData; // I get an error
    captureFunc(01).then((e)=> print(e)); // here I want to access the string inside the future object.
    // I am expecting to get: this is a future string 01.
    }

Future 对象是异步的,这意味着程序在调用时不会等待它完成,因此您必须让它等待使用 await 关键字返回的值或使用 futurebuilder.

因此,在您发布的代码中,您需要在打印对象值之前添加等待。 then 在这里不起作用,因为它已经在 getData() returns 未来对象之前完成了 运行 程序,因此它永远不会被调用。 你想把代码修改成这样:

main(){
int data = await getData();
print(data);
}

如需进一步阅读,请点击此处: https://dart.dev/codelabs/async-await

这一行造成了错误。

print(captureFunc(01)).then((e)=> print(e));

print 是一个带有 void return 的简单内置函数,因此它会产生错误。您应该先调用 captureFunc,然后使用回调来打印类似 -

的结果
captureFunc(01).then((e)=> print(e));

此外,如果您想避免使用和链接 then 回调,那么您可以将 async-await 与 main 一起使用,因为 captureFunc return 以后上面的代码可以像这样清理 -

Future<String> getData(int number) async {
  var thisFuture = await Future.delayed(Duration(seconds: 1), () {
    return 'this is a future string $number.';
  });
  return thisFuture;
}

main() async {
  var captureFunc = getData;
  print(await captureFunc(01));
}

async-await 只是一种定义异步函数并使用其结果的声明方式,它提供了语法糖来帮助您编写涉及 futures 的干净代码。

希望对您有所帮助!