[英]How to get primitive value from Future object (Future<int>) in flutter?
[英]How can we get value from future method in flutter?
我有这个 function 返回存储在其中的“SharedPreference”值。
Future<bool> getLoginStatus() async {
final prefs = await SharedPreferences.getInstance();
final loggedInStatus = prefs.getBool("loggedInStatus");
if (loggedInStatus == null) {
return false;
}
return loggedInStatus;
}
以上 function 是在名为“Constants.dart”的 class 中。 当我通过在不同的 class 中进行简单打印来测试从“getLoginStatus()”function 中提取值时。
print("Login status : " + Constants().getLoginStatus().toString());
它在下面给我一个 output。 为什么是“‘未来’的实例”? 为什么不简单的真假?
I/flutter (19683): Login status : Instance of 'Future<bool>'
由于您的 getLoginStatus() 是异步的,并且将来会返回一个布尔值。 因此,要获得值,您必须等待进程返回它。
因此,检索该值的正确代码是:
bool loggedInStatus = await Constants().getLoginStatus();
print(loggedInStatus);
您可以使用等待获取数据。
var data = await Constants().getLoginStatus();
print(data);
getLoginStatus().then((val){ print("Login status : $val"});
然后 function 应该与 Futures 一起使用以访问从未来返回的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.