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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…