Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/flutter/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Flutter 通过类访问SharedReferences方法_Flutter_Dart - Fatal编程技术网

Flutter 通过类访问SharedReferences方法

Flutter 通过类访问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

我有一个单独的文件,其中包含一个带有函数的类:

getstatus.dart

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...
}