Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/docker/10.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 颤振:什么';默认值的良好实践(关于共享的_首选项)_Flutter_Sharedpreferences_Conventions - Fatal编程技术网

Flutter 颤振:什么';默认值的良好实践(关于共享的_首选项)

Flutter 颤振:什么';默认值的良好实践(关于共享的_首选项),flutter,sharedpreferences,conventions,Flutter,Sharedpreferences,Conventions,我对我的代码没有任何问题,它工作完美,所以如果你不想浪费时间,就不要阅读。 我只是想从更有经验的人那里了解一下,你认为什么是更好的做法,所以这里有一件事: _initPrefs() async { if (prefs == null) prefs = await SharedPreferences.getInstance(); } setSoundEnabled(bool value) async { await _initPrefs(); print('

我对我的代码没有任何问题,它工作完美,所以如果你不想浪费时间,就不要阅读。

我只是想从更有经验的人那里了解一下,你认为什么是更好的做法,所以这里有一件事:

  _initPrefs() async {
    if (prefs == null) prefs = await SharedPreferences.getInstance();
  }

  setSoundEnabled(bool value) async {
    await _initPrefs();

    print('setSoundEnabled($value)');
    prefs.setBool(SharedPrefsKeys.soundEnabledKey, value);
  }

  //First alternative
  Future<bool> isSoundEnabled() async {
    await _initPrefs();

    bool value = prefs.getBool(SharedPrefsKeys.soundEnabledKey) ?? true;

    print('isSoundEnabled(): $value');
    return value;
  }

  //Second alternative
  Future<bool> isSoundEnabledAlternative() async {
    await _initPrefs();

    bool value = prefs.getBool(SharedPrefsKeys.soundEnabledKey);
    if (value == null) {
      value = true;
      setSoundEnabled(value); //no need to await this
    }

    print('isSoundEnabled(): $value');
    return value;
  }
\u initPrefs()异步{
如果(prefs==null)prefs=wait SharedPreferences.getInstance();
}
setSoundEnabled(布尔值)异步{
等待_initPrefs();
打印('setSoundEnabled($value');
prefs.setBool(SharedPrefskys.soundEnabledKey,值);
}
//第一种选择
未来isSoundEnabled()异步{
等待_initPrefs();
bool值=prefs.getBool(SharedPrefskys.soundEnabledKey)??为真;
打印('isSoundEnabled():$value');
返回值;
}
//第二种选择
Future isSoundEnabledAlternative()异步{
等待_initPrefs();
bool值=prefs.getBool(SharedPrefskys.soundEnabledKey);
如果(值==null){
值=真;
setSoundEnabled(值);//无需等待此操作
}
打印('isSoundEnabled():$value');
返回值;
}
这是我的一些应用程序设置代码,更具体地说是关于应用程序中是否应该启用声音

在第一个备选方案中:
如果
soundEnabledKey
没有值,我只返回默认的常量值
true
(不将其存储在共享的prefs中)

这意味着,如果用户从未更改此设置,则不会为
soundEnabledKey
存储任何值,并且该方法将始终返回该常量
true

在第二种选择中:
如果
soundEnabledKey
没有值,我首先保存该键的默认值
true
,然后返回该值


这意味着,无论用户是否更改此设置,第一次调用此方法时,应用程序将在共享prefs中存储
soundEnabledKey
的值,并且所有后续调用都将从共享prefs中检索该值。

我认为解决方案1更好,每个方法只有一个职责,并因此关闭以进行修改


但是,无论您在何处添加业务初始化代码,您都可以初始化soundEnabled值,以确保一致性

,只要您可以轻松地初始化soundEnabledKey,我会选择选项2,b/c更为一致,因为您只返回首选项值,而不必在尝试检索值时包含业务逻辑。