Flutter 通过类访问SharedReferences方法
我有一个单独的文件,其中包含一个带有函数的类: getstatus.dartFlutter 通过类访问SharedReferences方法,flutter,dart,Flutter,Dart,我有一个单独的文件,其中包含一个带有函数的类: getstatus.dart class GetStatus { isActive() async { SharedPreferences prefs = await SharedPreferences.getInstance(); bool boolValue = prefs.getBool('notification') ?? false; return boolValue; } } 要访问函数:final b
class GetStatus {
isActive() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
bool boolValue = prefs.getBool('notification') ?? false;
return boolValue;
}
}
要访问函数:
final bool getStatus=getStatus().isActive()代码>。然而,颤振给了我一个错误类型“Future”不是类型“bool”的子类型
。可能isActive()方法是错误的,但我到底应该更改什么?顺便说一句:返回值必须是bool。将签名更改为:
Future<bool> isActive() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
return prefs.getBool('notification') ?? false;
}
现在您可以使用activeValue
作为bool
要处理Dart中的期货,请转到以下文档:prefs.getBool
不会返回您的Future
,而是bool
。是的,我收到以下消息:错误:“Future”类型的值不能分配给“bool”类型的变量。
将final bool getStatus…
更改为final Future getStatus…
有效。但我需要“bool”中的值。有什么想法吗?谢谢,伙计,但我有点困惑。我应该把这行代码放在哪里?@Bassam我更新了答案,基本上取决于你的应用程序,你在哪里调用这个方法,你需要在异步调用中使用wait或使用'on complete'方法:然后(…)或whenComplete(…),等等
fecthActive() async {
var activeValue = await getStatusInstance.isActive();
//do something else...
}