Sub topic 2
Saving Settings with `shared_preferences`
This chapter assumes basic Dart classes, null safety, Future, async, and await. You should also know how to add a Flutter package through pubspec.yaml.
A setting is small application data such as whether dark mode is enabled, which language the user selected, or whether an introductory screen was dismissed. For these values, use the shared_preferences package. It stores simple key-value pairs on the device.
A key-value pair connects a string key to one supported value:
| Value type | Example |
|---|---|
| `bool` | `true` for dark mode |
| `int` | `10` for a page size |
| `double` | `1.5` for text scale |
| `String` | `"en"` for a language |
| `List<String>` | `["red", "blue"]` for selected labels |
The storage is persistent, so a value remains after the app closes and starts again. It is not a database. You cannot efficiently search rows or model relationships with it.
Write and read a boolean setting
SharedPreferences.getInstance() returns a Future, because opening or loading the platform storage can take time. Always wait for it with await.
import 'package:shared_preferences/shared_preferences.dart';
Future<void> saveDarkMode(bool value) async {
final prefs = await SharedPreferences.getInstance();
await prefs.setBool('dark_mode', value);
}
Future<bool> loadDarkMode() async {
final prefs = await SharedPreferences.getInstance();
return prefs.getBool('dark_mode') ?? false;
}setBool writes the value under the dark_mode key. getBool returns a nullable bool: it returns null when the key has never been stored. The ?? false expression supplies the default value for that first launch.
You can use the same pattern for other supported types:
Future<void> saveLanguage(String language) async {
final prefs = await SharedPreferences.getInstance();
await prefs.setString('language', language);
}
Future<String> loadLanguage() async {
final prefs = await SharedPreferences.getInstance();
return prefs.getString('language') ?? 'en';
}
Future<void> clearLanguage() async {
final prefs = await SharedPreferences.getInstance();
await prefs.remove('language');
}remove deletes one setting. Use it when a user signs out or when a setting should return to its initial state.
The working model
Think of preferences as a small local dictionary:
The key is part of your data contract. Changing dark_mode to darkMode creates a different entry. Keep keys in one place to avoid spelling mistakes.
Common errors
- Forgetting
await: A read returns aFuture, not the final value. - Using the wrong getter: A value saved with
setIntmust be read withgetInt. - Assuming a key always exists: New installations have no saved values. Provide a default.
- Saving every rebuild: Do not write preferences from a widget's
buildmethod. Save only when the setting changes. - Treating preferences as authoritative server data: Preferences belong to one device and can be cleared by the user or operating system.
- Ignoring the returned
Future: Await writes when later code depends on the value being saved.
For a setting used by several widgets, place these functions in a service or repository rather than repeating package calls throughout the UI. This gives the setting one key, one default, and one location for future changes.
Exercise
What does loadDarkMode() return when the dark_mode key has never been written?
Show answer
It returns false, because getBool returns null and the null-coalescing operator supplies false.