我在我的Ffltter应用程序中使用共享首选项,我想做的是在启动时将SharedPreferences存储为一个字段,然后在应用程序中同步使用它.然而,我不确定我是否没有错过任何东西. 我想要实现的不是:

method1() async {
  SharedPreferences sp = await SharedPreferences.getInstance();
  return sp.getString('someKey');
}

SharedPreferences sp;
//I would probably pass SharedPreferences in construc至r, but the idea is the same
someInitMethod() async {
  sp = await SharedPreferences.getInstance();
}
method1() {
  return sp.getString('someKey');
}
method2() {
  return sp.getString('someKey2');
}
method3() {
  return sp.getString('someKey3');
}

In that way I would achieve synchronous access 至 sharedPrefs. Is it bad solution?

EDIT:
What is worth mentioning is that getInstance method will only check for instance and if there is any than it returns it, so as I see it, is that async is only needed 至 initialize instance. And both set and get methods are sync anyway.

static Future<SharedPreferences> getInstance() async {
  if (_instance == null) {
    final Map<String, Object> fromSystem =
        await _kChannel.invokeMethod('getAll');
    assert(fromSystem != null);
    // Strip the flutter. prefix from the returned preferences.
    final Map<String, Object> preferencesMap = <String, Object>{};
    for (String key in fromSystem.keys) {
      assert(key.startsWith(_prefix));
      preferencesMap[key.substring(_prefix.length)] = fromSystem[key];
    }
    _instance = new SharedPreferences._(preferencesMap);
  }
  return _instance;
}

推荐答案

我使用与原始海报建议的方法相同的方法,即我有一个全局变量(实际上是一个用于所有此类变量的类中的静态字段),我将其初始化为共享首选项,如下所示:

globals.dart年内:

class App {      
  static SharedPreferences localStorage;
  static Future init() async {
    localStorage = await SharedPreferences.getInstance();
  }
}

main.dart年内:

void main() {
  start();
}

Async.Future start() async {
  await App.init();
  localStorage.set('userName','Bob');
  print('User name is: ${localStorage.get('userName)'}');  //prints 'Bob'
}

上面的方法运行良好,但我发现如果我try 使用另一个DART文件(例如settings.dart)中的App.localStorage,它将不起作用,因为App.localStorage是NULL,但是我不能理解它是如何变成NULL的.

问题是settings.dart中的import语句是import 'package:<packagename>/src/globals.dart';,而它本应该是import 'globals.dart;.

Dart相关问答推荐

从扩展类访问抽象类属性

VS Code 无法识别 Flutter 中的单元测试

Card宽度与父级匹配

如何将指针事件发送到堆栈中的低级子级

AngularDart 可以直接路由到组件吗?

StreamBuilder 会在无状态小部件中自动关闭流吗?

Flutter - 如何自动启用 AnimatedOpacity?

Flatter中的Sqlite,数据库assets如何工作

Flutter有向图.我可以将CustomPainter类与自定义小部件一起使用吗?

Flutter-在屏幕上绘制图形

如何判断一个字符串是否可以是 json.decode

如何从JSON对象获取格式化/缩进的JSON字符串?

对该常量表达式的求值会抛出一个表达式

在 Flutter 的 TextFormField 中管理事件

Dart vs Haxe - Current state, hype, usability, ...?

以编程方式使dart中的十六进制 colored颜色 变亮或变暗

可选参数的默认值必须是常量

用默认值初始化成员的最优雅的方法

Dart 中的多行字符串

有没有办法在 Dart 中通过引用传递原始参数?