On this page14 sections
Lecture 007: Remembering the Theme
| Category | 3: SharedPreferences |
| Lecture | 007 of 008 |
| Estimated video length | 14 min |
| Target | Flutter 3.44 · Dart 3.12 · provider 6.1 · shared_preferences 2.5 |
| Level | Beginner |
Now we join the two halves: the
ThemeProvider(Lectures 004–005) saves every change to SharedPreferences (Lecture 006), and the app loads the saved choice before its first frame. No flash of the wrong theme, and the choice survives every restart.
Contents
Prerequisites · Connection · Objectives · Lesson · Code Examples · Common Mistakes · Best Practices · Mini Challenge · Practice Questions · Answers · Takeaways · Full Code
Prerequisites
Lectures 004–006.
Connection With Previous Lectures
ThemeProvider gains a load() method and saves inside setThemeMode(). main() becomes
async so it can load before runApp.
Learning Objectives
- Save an enum (
ThemeMode) as aStringwith.name - Turn the saved
Stringback into aThemeMode - Load settings in
main()beforerunApp, withWidgetsFlutterBinding.ensureInitialized() - Hand an existing object to Provider with
ChangeNotifierProvider.value - Save inside the provider every time the setting changes
1. What to Save
SharedPreferences can't store a ThemeMode directly, but every enum value has a .name:
ThemeMode.dark.name // 'dark'To read it back, find the value whose name matches, with a fallback for "nothing saved" or junk data:
final mode = ThemeMode.values.firstWhere(
(m) => m.name == saved,
orElse: () => ThemeMode.system,
);2. The Saving ThemeProvider
lib/theme_provider.dart
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
class ThemeProvider extends ChangeNotifier {
ThemeProvider(this._prefs, this._themeMode);
static const _key = 'theme_mode';
final SharedPreferences _prefs;
ThemeMode _themeMode;
ThemeMode get themeMode => _themeMode;
bool get isDark => _themeMode == ThemeMode.dark;
/// Reads the saved choice once, before the app starts.
static Future<ThemeProvider> load() async {
final prefs = await SharedPreferences.getInstance();
final saved = prefs.getString(_key);
final mode = ThemeMode.values.firstWhere(
(m) => m.name == saved,
orElse: () => ThemeMode.system,
);
return ThemeProvider(prefs, mode);
}
Future<void> setThemeMode(ThemeMode mode) async {
if (mode == _themeMode) return;
_themeMode = mode;
notifyListeners();
await _prefs.setString(_key, mode.name);
}
}load()is a static method (Dart Basic 036): it builds a ready-to-use provider from the saved data.setThemeModeupdates the screen first (notifyListeners()), then saves. The UI never waits for the disk.- If nothing is saved yet, the app follows the phone (
ThemeMode.system).
3. Loading Before the App Starts
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
final themeProvider = await ThemeProvider.load();
runApp(
ChangeNotifierProvider.value(
value: themeProvider,
child: const NotesApp(),
),
);
}WidgetsFlutterBinding.ensureInitialized()must come first: plugins like shared_preferences talk to Android/iOS, and that connection has to be set up beforerunAppwould normally do it.await ThemeProvider.load()reads the setting before the first frame, so the app opens in the right theme straight away.ChangeNotifierProvider.valuehands Provider an object that already exists. (Usecreatewhen Provider should make the object; use.valuewhen you made it yourself.)
Code Examples
Example 1: My Notes That Remembers Dark Mode
lib/theme_provider.dart: as in Section 2.
lib/main.dart
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'theme_provider.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
final themeProvider = await ThemeProvider.load();
runApp(
ChangeNotifierProvider.value(
value: themeProvider,
child: const NotesApp(),
),
);
}
ThemeData buildTheme(Brightness brightness) {
return ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.teal, brightness: brightness),
);
}
class NotesApp extends StatelessWidget {
const NotesApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'My Notes',
debugShowCheckedModeBanner: false,
theme: buildTheme(Brightness.light),
darkTheme: buildTheme(Brightness.dark),
themeMode: context.watch<ThemeProvider>().themeMode,
home: const HomeScreen(),
);
}
}
class HomeScreen extends StatelessWidget {
const HomeScreen({super.key});
@override
Widget build(BuildContext context) {
final theme = context.watch<ThemeProvider>();
return Scaffold(
appBar: AppBar(title: const Text('My Notes')),
body: SwitchListTile(
title: const Text('Dark mode'),
value: theme.isDark,
onChanged: (value) => context.read<ThemeProvider>().setThemeMode(
value ? ThemeMode.dark : ThemeMode.light,
),
),
);
}
}Try it: turn dark mode on, then stop the app completely (not just hot restart) and run it again. It opens in dark mode immediately.
Tested: with nothing saved, load() gave ThemeMode.system; with 'dark' saved, it gave
ThemeMode.dark; with junk ('purple') saved, it fell back to system. Flipping the switch
saved 'dark', and a fresh load() (a simulated restart) came back in dark mode.
Common Beginner Mistakes
1. Forgetting WidgetsFlutterBinding.ensureInitialized(): calling
SharedPreferences.getInstance() in main() before it can crash at startup, because the
connection to the platform isn't ready yet. Make it the first line of an async main.
2. Loading inside build: calling SharedPreferences.getInstance() in a build method runs
it on every rebuild and shows the wrong theme until it finishes. Load once, in main().
3. Saving but not notifying (or the other way round): without notifyListeners() the screen
doesn't change; without setString the choice is lost on restart. setThemeMode does both.
4. ChangeNotifierProvider(create: ...) with an existing object: writing
create: (_) => themeProvider for an object you already built works, but .value is the
intended way, and it's clearer about who owns the object.
Best Practices
- Load all settings once, in
main(), beforerunApp. - Save inside the provider method that changes the setting, so you can't forget.
- Update the UI first, then save.
- Always have a fallback for missing or unreadable saved values.
Mini Challenge
Add a third option. Replace the switch with three ListTiles (Light, Dark, System), each calling
setThemeMode with its mode, and show a check icon (trailing: Icon(Icons.check)) on the current
one. Restart the app and confirm "System" is remembered too.
Practice Questions
- How do you turn
ThemeMode.lightinto aStringto save? - Why does
load()useorElse? - What must be the first line of
main()when loading SharedPreferences there? - When do you use
ChangeNotifierProvider.valueinstead ofcreate? - Why does
setThemeModecallnotifyListeners()before saving?
Practice Answers
ThemeMode.light.name, which gives'light'.- To fall back to
ThemeMode.systemwhen nothing (or something unknown) was saved. WidgetsFlutterBinding.ensureInitialized();- When the object already exists (you created it yourself, e.g. with
await load()). - So the screen updates immediately; saving to disk happens in the background.
Key Takeaways
- Save enums by
.name; read them back withvalues.firstWhere(..., orElse: ...). async main():ensureInitialized(),await load(), thenrunApp.ChangeNotifierProvider.valueprovides an object you already created.- The provider both notifies and saves on every change, so the theme survives restarts.
Full Code (Copy-Paste Reference)
Everything the app needs up to and including this lecture, file by file.
lib/theme_provider.dart
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
class ThemeProvider extends ChangeNotifier {
ThemeProvider(this._prefs, this._themeMode);
static const _key = 'theme_mode';
final SharedPreferences _prefs;
ThemeMode _themeMode;
ThemeMode get themeMode => _themeMode;
bool get isDark => _themeMode == ThemeMode.dark;
/// Reads the saved choice once, before the app starts. Falls back to the phone's
/// own setting when nothing (or something unreadable) was saved.
static Future<ThemeProvider> load() async {
final prefs = await SharedPreferences.getInstance();
final saved = prefs.getString(_key);
final mode = ThemeMode.values.firstWhere(
(m) => m.name == saved,
orElse: () => ThemeMode.system,
);
return ThemeProvider(prefs, mode);
}
Future<void> setThemeMode(ThemeMode mode) async {
if (mode == _themeMode) return;
_themeMode = mode;
notifyListeners(); // update the screen first
await _prefs.setString(_key, mode.name); // then persist, in the background
}
}lib/main.dart
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'theme_provider.dart';
Future<void> main() async {
// Must come first: plugins like shared_preferences need the platform channel ready.
WidgetsFlutterBinding.ensureInitialized();
// Reads the saved theme BEFORE the first frame - no flash of the wrong theme.
final themeProvider = await ThemeProvider.load();
runApp(
// .value because this ThemeProvider already exists - Provider doesn't create it.
ChangeNotifierProvider.value(
value: themeProvider,
child: const NotesApp(),
),
);
}
ThemeData buildTheme(Brightness brightness) {
return ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.teal, brightness: brightness),
);
}
class NotesApp extends StatelessWidget {
const NotesApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'My Notes',
debugShowCheckedModeBanner: false,
theme: buildTheme(Brightness.light),
darkTheme: buildTheme(Brightness.dark),
themeMode: context.watch<ThemeProvider>().themeMode,
home: const HomeScreen(),
);
}
}
class HomeScreen extends StatelessWidget {
const HomeScreen({super.key});
@override
Widget build(BuildContext context) {
final theme = context.watch<ThemeProvider>();
return Scaffold(
appBar: AppBar(title: const Text('My Notes')),
body: SwitchListTile(
title: const Text('Dark mode'),
value: theme.isDark,
onChanged: (value) => context.read<ThemeProvider>().setThemeMode(
value ? ThemeMode.dark : ThemeMode.light,
),
),
);
}
}