In a Flutter app, persisting data across app sessions is essential to ensure a smooth user experience. One way of doing this is by using the SharedPreferences package. This package allows users to store and retrieve primitive data types such as integers, booleans, and strings.
To use the package, add the following line to your pubspec.yaml file:
dependencies:
shared_preferences: ^2.0.6}
Then, import the package in your dart file:
import 'package:shared_preferences/shared_preferences.dart';}
To save data, create an instance of SharedPreferences and call the appropriate method for the data type you are storing. For example, to save a boolean value:
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setBool('isDarkMode', true);}
To retrieve the saved data, call the appropriate getter method:
SharedPreferences prefs = await SharedPreferences.getInstance();
bool isDarkMode = prefs.getBool('isDarkMode') ?? false;}
Note that the ?? operator ensures that if the value retrieved from the SharedPreferences is null, a default value of false is used instead.
Additionally, you can also delete a single preference:
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.remove('isDarkMode');}
Or delete all preferences:
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.clear();}
The SharedPreferences package provides a simple and efficient way to persist data in your Flutter app.
Example Usage:class AppSettings {
static final AppSettings _instance = AppSettings._internal();
factory AppSettings() {
return _instance;
}
AppSettings._internal();
final _themeModeSource = BehaviorSubject.seeded(defaultThemeMode);
static const String themeModePrefsKey = "themeMode";
Future _prefs = SharedPreferences.getInstance();
Future getThemeMode() async {
final SharedPreferences prefs = await _prefs;
final String prefThemeModeString = prefs.getString(themeModePrefsKey) ?? 'system';
return ThemeModeUtils.stringToThemeMode(prefThemeModeString);
}
Future setThemeMode(ThemeMode mode) async {
final SharedPreferences prefs = await _prefs;
prefs.setString(themeModePrefsKey, ThemeModeUtils.themeModeToString(mode));
_themeModeSource.add(mode);
}
Stream getThemeModeStream() async* {
yield await getThemeMode();
yield* _themeModeSource.stream;
}
}