gpt4 book ai didi

object - Dart 和 flutter : Need help understanding how to capture futures

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

我正在学习 Dart 语言中的 Future 对象,并且一直在尝试使用它们。我想创建一个包含 future 对象的异步函数。
后者应该返回一个字符串,并且函数应该返回 future 返回的任何内容。
我知道我的文字不太好,但这里是代码和评论:

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.
}
我得到了异常(exception):
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.
请帮助我了解函数内部的 future 、 future 以及如何从包含 future 类型对象的函数中获取值。

最佳答案

此行正在创建错误。

print(captureFunc(01)).then((e)=> print(e));
print 是一个带有 void 返回的简单内置函数,因此会产生错误。您应该首先调用 captureFunc 并使用然后回调来打印结果,例如 -
captureFunc(01).then((e)=> print(e));
此外,如果您想避免使用和链接 then 回调,那么您可以将 async-await 与 main 一起使用,因为 captureFunc return future 上面的代码可以这样清理 -
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 只是一种定义异步函数并使用其结果的声明性方式,它提供了语法糖来帮助您编写涉及 future 的干净代码。
希望这可以帮助!

关于object - Dart 和 flutter : Need help understanding how to capture futures,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62546445/

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