On this page14 sections
  1. Prerequisites
  2. Connection With Previous Lectures
  3. Learning Objectives
  4. 1. What to Save
  5. 2. The Saving ThemeProvider
  6. 3. Loading Before the App Starts
  7. Code Examples
  8. Common Beginner Mistakes
  9. Best Practices
  10. Mini Challenge
  11. Practice Questions
  12. Practice Answers
  13. Key Takeaways
  14. Full Code (Copy-Paste Reference)

Lecture 007: Remembering the Theme

Category3: SharedPreferences
Lecture007 of 008
Estimated video length14 min
TargetFlutter 3.44 · Dart 3.12 · provider 6.1 · shared_preferences 2.5
LevelBeginner

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 a String with .name
  • Turn the saved String back into a ThemeMode
  • Load settings in main() before runApp, with WidgetsFlutterBinding.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:

dart
ThemeMode.dark.name     // 'dark'

To read it back, find the value whose name matches, with a fallback for "nothing saved" or junk data:

dart
final mode = ThemeMode.values.firstWhere(
  (m) => m.name == saved,
  orElse: () => ThemeMode.system,
);

2. The Saving ThemeProvider

lib/theme_provider.dart

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.
  • setThemeMode updates 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

dart
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 before runApp would normally do it.
  • await ThemeProvider.load() reads the setting before the first frame, so the app opens in the right theme straight away.
  • ChangeNotifierProvider.value hands Provider an object that already exists. (Use create when Provider should make the object; use .value when 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

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(), before runApp.
  • 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

  1. How do you turn ThemeMode.light into a String to save?
  2. Why does load() use orElse?
  3. What must be the first line of main() when loading SharedPreferences there?
  4. When do you use ChangeNotifierProvider.value instead of create?
  5. Why does setThemeMode call notifyListeners() before saving?

Practice Answers

  1. ThemeMode.light.name, which gives 'light'.
  2. To fall back to ThemeMode.system when nothing (or something unknown) was saved.
  3. WidgetsFlutterBinding.ensureInitialized();
  4. When the object already exists (you created it yourself, e.g. with await load()).
  5. So the screen updates immediately; saving to disk happens in the background.

Key Takeaways

  • Save enums by .name; read them back with values.firstWhere(..., orElse: ...).
  • async main(): ensureInitialized(), await load(), then runApp.
  • ChangeNotifierProvider.value provides 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

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

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,
            ),
      ),
    );
  }
}