Sub topic 11
Saving the User’s Theme Preference
This chapter assumes you know basic Dart syntax and null safety, can build Flutter widget trees, and understand MaterialApp, Scaffold, and BuildContext. The goal is to keep a user’s light, dark, or system choice after the app closes.
Store a Stable Value
ThemeMode is an enum. An enum is a type with a fixed set of named values: light, dark, and system.
The shared_preferences package stores small key-value settings on the device. Store the enum’s name instead of its numeric index. Names are easier to understand and do not depend on the order of enum values.
Add the package to pubspec.yaml, then run flutter pub get:
dependencies:
flutter:
sdk: flutter
shared_preferences: ^2.5.3Create functions that translate between the saved string and ThemeMode:
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter/material.dart';
Future<ThemeMode> loadThemeMode() async {
final preferences = await SharedPreferences.getInstance();
final savedName = preferences.getString('themeMode');
return ThemeMode.values.firstWhere(
(mode) => mode.name == savedName,
orElse: () => ThemeMode.system,
);
}
Future<void> saveThemeMode(ThemeMode mode) async {
final preferences = await SharedPreferences.getInstance();
await preferences.setString('themeMode', mode.name);
}The fallback is important. A user may be running an older app version with no saved value, or a future version may no longer recognize an old value. In both cases, ThemeMode.system gives the app a safe default.
Load Before Building the App
Load the preference before calling runApp. This prevents the app from first showing one theme and then changing to another after startup.
The following example combines loading, switching, and saving. It assumes the shared_preferences dependency is installed.
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
Future<ThemeMode> loadThemeMode() async {
final preferences = await SharedPreferences.getInstance();
final savedName = preferences.getString('themeMode');
return ThemeMode.values.firstWhere(
(mode) => mode.name == savedName,
orElse: () => ThemeMode.system,
);
}
Future<void> saveThemeMode(ThemeMode mode) async {
final preferences = await SharedPreferences.getInstance();
await preferences.setString('themeMode', mode.name);
}
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
final initialMode = await loadThemeMode();
runApp(App(initialMode: initialMode));
}
class App extends StatefulWidget {
const App({required this.initialMode, super.key});
final ThemeMode initialMode;
@override
State<App> createState() => _AppState();
}
class _AppState extends State<App> {
late ThemeMode mode;
@override
void initState() {
super.initState();
mode = widget.initialMode;
}
@override
Widget build(BuildContext context) {
const seed = Color(0xFF6750A4);
return MaterialApp(
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: seed),
),
darkTheme: ThemeData(
colorScheme: ColorScheme.fromSeed(
seedColor: seed,
brightness: Brightness.dark,
),
),
themeMode: mode,
home: Scaffold(
appBar: AppBar(title: const Text('Theme settings')),
body: Center(
child: 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) async {
final newMode = selection.first;
setState(() => mode = newMode);
await saveThemeMode(newMode);
},
),
),
),
);
}
}The theme changes immediately through setState. The following await writes the same choice for the next launch.
Startup Flow
Exercise
Why should the app use ThemeMode.system when the stored string is missing or invalid?
Show answer
It provides a predictable fallback and avoids crashing when the preference cannot be trusted or does not exist.