Sub topic 11
Saving the user's theme preference
This chapter assumes you have a working light, dark and system theme setup, and a runtime switcher driven by a ValueNotifier<ThemeMode>. You should also be comfortable with async/await and BuildContext. The goal is to make the user's choice survive an app restart, without a flash of the wrong theme at launch.
What needs to be saved
The only value to store is the ThemeMode: light, dark or system. Don't store the ThemeData or the ColorScheme. Both are rebuilt from the seed color on every launch, so saving them only adds a way for stored data to go out of date.
Store the mode by its enum name, such as "dark", and not by its index. Indexes change if the enum is reordered or extended. Names stay readable in the stored file and survive refactoring.
| Option | Stored value | Survives a reorder of the enum? | Notes |
|---|---|---|---|
| `mode.index` | `0`, `1`, `2` | No | A silent bug if Flutter ever changes the order. |
| `mode.name` | `"system"` | Yes | Readable, and a bad value is easy to detect. |
| `mode.toString()` | `"ThemeMode.dark"` | Yes | Needs parsing. It adds nothing over `name`. |
Reading and writing with shared_preferences
The shared_preferences package stores small key-value pairs on every Flutter platform. It uses NSUserDefaults on iOS and macOS, a preferences file on Android, and localStorage on the web. Add it with flutter pub add shared_preferences.
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
Future<ThemeMode> loadThemeMode() async {
final prefs = await SharedPreferences.getInstance();
final name = prefs.getString('themeMode');
return ThemeMode.values.asNameMap()[name] ?? ThemeMode.system;
}
Future<void> saveThemeMode(ThemeMode mode) async {
final prefs = await SharedPreferences.getInstance();
await prefs.setString('themeMode', mode.name);
}ThemeMode.values.asNameMap() returns a Map<String, ThemeMode>. Looking up null (nothing saved yet) or an unknown string (a stale or corrupted value) returns null, and ?? turns that into ThemeMode.system. A first launch and a broken value therefore follow the same path, and the app never crashes on bad data.
Avoiding the flash of the wrong theme
SharedPreferences.getInstance() is asynchronous. If you call runApp first and load the preference afterwards, the app paints one frame with the default mode and then switches. A user who chose dark sees a white flash on every launch.
The fix is to load the value before the first frame. In main, call WidgetsFlutterBinding.ensureInitialized(), which is required before using plugins ahead of runApp. Then await the load and pass the result into the app.
A controller that saves on change
Scattering saveThemeMode calls across widgets invites bugs, because one forgotten call means one setting that isn't saved. Put the load and the save in one object that extends ValueNotifier<ThemeMode>. MaterialApp already listens to it through ValueListenableBuilder.
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
class ThemeController extends ValueNotifier<ThemeMode> {
ThemeController(ThemeMode mode) : super(mode);
static const _key = 'themeMode';
static Future<ThemeController> load() async {
final prefs = await SharedPreferences.getInstance();
final mode = ThemeMode.values.asNameMap()[prefs.getString(_key)];
return ThemeController(mode ?? ThemeMode.system);
}
Future<void> setMode(ThemeMode mode) async {
if (mode == value) return;
value = mode; // update the UI first
final prefs = await SharedPreferences.getInstance();
await prefs.setString(_key, mode.name);
}
}setMode assigns value before it awaits storage. The UI changes immediately, and the disk write happens afterwards. If the write fails, the user keeps the new theme for this session and the old preference returns on the next launch. That is an acceptable failure for a cosmetic setting. The early return on an unchanged mode avoids a pointless write.
The complete app
This version puts everything in one file. The seed color and the two ThemeData objects are the same as in the earlier chapters.
import 'package:flutter/material.dart';
import 'theme_controller.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
final controller = await ThemeController.load();
runApp(App(controller: controller));
}
class App extends StatelessWidget {
const App({super.key, required this.controller});
final ThemeController controller;
@override
Widget build(BuildContext context) {
const seed = Color(0xFF6750A4);
return ValueListenableBuilder<ThemeMode>(
valueListenable: controller,
builder: (context, mode, _) {
return MaterialApp(
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: seed),
),
darkTheme: ThemeData(
colorScheme: ColorScheme.fromSeed(
seedColor: seed,
brightness: Brightness.dark,
),
),
themeMode: mode,
home: SettingsPage(controller: controller),
);
},
);
}
}
class SettingsPage extends StatelessWidget {
const SettingsPage({super.key, required this.controller});
final ThemeController controller;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Settings')),
body: Center(
child: ValueListenableBuilder<ThemeMode>(
valueListenable: controller,
builder: (context, mode, _) {
return SegmentedButton<ThemeMode>(
segments: const [
ButtonSegment(value: ThemeMode.light, label: Text('Light')),
ButtonSegment(value: ThemeMode.system, label: Text('System')),
ButtonSegment(value: ThemeMode.dark, label: Text('Dark')),
],
selected: {mode},
onSelectionChanged: (selection) {
controller.setMode(selection.first);
},
);
},
),
),
);
}
}The SegmentedButton sits inside its own ValueListenableBuilder. In the earlier version, SettingsPage read themeModeNotifier.value directly in build. Because the page doesn't subscribe to the notifier, nothing guarantees it rebuilds when the value changes, so the highlighted segment can lag behind the real mode. Subscribing in the widget that displays the value keeps the two in sync.
Edge cases
- First launch. No key exists,
getStringreturnsnull, and the app usesThemeMode.system. This is the right default because it respects the device setting until the user chooses otherwise. - Unknown stored value. A name that is not in the enum falls back to
system. This can happen after a downgrade or a manual edit on the web. - Slow storage. The load happens before the first frame, so a slow read delays startup. For one small string this is typically a few milliseconds. If you also load other data in
main, run the loads together withFuture.wait. - Multiple isolates or processes.
SharedPreferencescaches values in memory per isolate. If a background isolate writes the key, the main isolate won't see it until you callprefs.reload(). Most apps never hit this. - Newer API. Recent
shared_preferencesversions also provideSharedPreferencesAsyncandSharedPreferencesWithCache. They avoid the stale-cache problem above. Check the package documentation for the version you use. The controller pattern stays the same, and only the two storage calls change. - Platform bar colors. The status bar and navigation bar may need their own style update when the mode changes. Reading
Theme.of(context).brightnessin a widget belowMaterialAppis the usual way to do this.
Testing the fallback
setMockInitialValues replaces the real storage with an in-memory map, so tests need no device. This example assumes the controller lives in lib/theme_controller.dart and the package is named my_app.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:my_app/theme_controller.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() {
test('uses the saved mode', () async {
SharedPreferences.setMockInitialValues({'themeMode': 'dark'});
final controller = await ThemeController.load();
expect(controller.value, ThemeMode.dark);
});
test('falls back to system for an unknown value', () async {
SharedPreferences.setMockInitialValues({'themeMode': 'purple'});
final controller = await ThemeController.load();
expect(controller.value, ThemeMode.system);
});
test('setMode writes the enum name', () async {
SharedPreferences.setMockInitialValues({});
final controller = await ThemeController.load();
await controller.setMode(ThemeMode.light);
final prefs = await SharedPreferences.getInstance();
expect(prefs.getString('themeMode'), 'light');
});
}Common mistakes
- Loading the preference after
runApp, which causes a flash of the wrong theme at launch. - Saving
mode.index, which breaks if the enum order ever changes. - Forgetting to handle
nullor unknown values, which crashes the first launch. - Saving from many widgets instead of one controller, so some paths skip the write.
- Skipping
ensureInitialized()inmain.
Exercise
A user picks Dark, closes the app, and reopens it. The app starts in light mode for one frame and then turns dark. The code calls runApp(App()) first and then runs loadThemeMode().then(...) to set the notifier. What is wrong and how do you fix it?
Show answer
The preference is read asynchronously after the first frame, so the first frame is built with the default mode. Make main async, call WidgetsFlutterBinding.ensureInitialized(), await the load (for example ThemeController.load()), and pass the loaded mode into the app before calling runApp.
Exercise
Your saved value is "system", and in a later release you add a new ThemeMode-like option to your own enum and insert it before system. Why does storing mode.name stay correct while storing mode.index does not, and what happens to an old install whose stored name no longer exists?
Show answer
Names identify the value, so the stored "system" still maps to system after the enum is reordered. Indexes identify a position, so the old number would now point at a different value. If a stored name no longer exists, asNameMap()[name] returns null and ?? ThemeMode.system supplies the default.