我们如何从未来的方法中获得价值? [英] How can we get value from future method in flutter?
问题描述
我有此函数返回存储在其中的"SharedPreference"值.
I have this function returning the "SharedPreference" value stored in it.
Future<bool> getLoginStatus() async {
final prefs = await SharedPreferences.getInstance();
final loggedInStatus = prefs.getBool("loggedInStatus");
if (loggedInStatus == null) {
return false;
}
return loggedInStatus;
}
上面的函数在名为"Constants.dart"的类中.当我通过在不同类中进行简单打印来进行从"getLoginStatus()"函数中提取值的测试时.
Above function is in the class named "Constants.dart". When I do the test of extracting value from "getLoginStatus()" function by simple printing in different class.
print("Login status : " + Constants().getLoginStatus().toString());
下面给出了我的输出.为什么是未来实例"?为什么不简单地选择对还是错呢?
It give me below as an output. Why "Instance of 'Future'"? Why not simple either true or false?
I/flutter (19683): Login status : Instance of 'Future<bool>'
推荐答案
由于您的getLoginStatus()是异步的,因此将来会返回布尔值.因此,要获取该值,您必须等待过程将其返回.
Since your getLoginStatus() is asynchronous and it return a bool value in future. So to get the value you have to await for the process to return it.
因此检索该值的正确代码将是:
So the correct Code to retrieve the value would be :
bool loggedInStatus = await Constants().getLoginStatus();
print(loggedInStatus);
这篇关于我们如何从未来的方法中获得价值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!