Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

sharedpreferences - Flutter: What's a good practice for default values (concerning shared_preferences)

I have no problem with my code, it works flawlessly, so if you don't want to waste your time, don't read.

I just want to know from more experienced guys, what do you think is a better practice, so here's the thing:

  _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;
  }

This is some of my code for app-settings, more specifically about wether or not sound should be enabled in the app.

In the first alternative:
In case there is no value for soundEnabledKey, I just return the default constant value true (without storing it in shared prefs).

This means, that if the user NEVER changes this setting, there will be NO value stored for soundEnabledKey and the method will always return that constant true.

In the second alternative:
In case there is no value for soundEnabledKey, I first save the default value true for that key, then I return that value.

This means, that no matter if the user ever changes this setting or not, the first time this method gets called, the app will store a value for the soundEnabledKey in shared prefs, and all subsequent calls will retrieve that value from shared prefs.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I think solution 1 is better, each method has only single responsibility, and is closed for modification because of this.

but you can initialize the soundEnabled value wherever you add your business initialization code, for the sake of consistency


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...