Flutter
Theme switching
Switch between multiple app themes at runtime.
Multi-themed app
In a multi-themed app you hold ThemeData in state. When the user changes the theme, the state is updated and MaterialApp is rebuilt. With ChangeNotifier you propagate this change across the whole app.
class ThemeModeNotifier extends ChangeNotifier {
ThemeMode _mode = ThemeMode.light;
ThemeMode get mode => _mode;
void toggle() {
_mode = _mode == ThemeMode.light
? ThemeMode.dark
: ThemeMode.light;
notifyListeners();
}
}
Theme management with Provider
With ChangeNotifierProvider you propagate the theme state app-wide. Consumer listens to theme changes and rebuilds MaterialApp with the new themeMode.
ChangeNotifierProvider(
create: (_) => ThemeModeNotifier(),
child: Consumer<ThemeModeNotifier>(
builder: (context, notifier, _) => MaterialApp(
theme: ThemeData.light(),
darkTheme: ThemeData.dark(),
themeMode: notifier.mode,
home: const HomeScreen(),
),
),
);
Exercise Write a theme controller
Write a ChangeNotifier named ThemeController. It has a bool field _isDark starting as false, exposed via an isDark getter. The toggle method flips the value and alerts listeners. In main, create it, call toggle, print isDark.
Show example solution
import 'package:flutter/material.dart';
class ThemeController extends ChangeNotifier {
bool _isDark = false;
bool get isDark => _isDark;
void toggle() {
_isDark = !_isDark;
notifyListeners();
}
}
void main() {
final controller = ThemeController();
controller.toggle();
print(controller.isDark);
}
Test yourself
-
Which method of ChangeNotifier notifies listeners about a theme change?
- build
- updateListeners
- notifyListeners
- setState
Show answer
notifyListeners — notifyListeners reports the change in ChangeNotifier to all listening widgets; Consumer and context.watch listen for this signal.
-
Toggle method
void toggle() {
_mode = (_mode == ThemeMode.light) ? ThemeMode.dark : ____;
notifyListeners();
}
Show answer
void toggle() {
_mode = (_mode == ThemeMode.light) ? ThemeMode.dark : ThemeMode.light;
notifyListeners();
}
-
Theme switching parts
- ChangeNotifier
- Notifies state changes
- notifyListeners
- Alerts listeners
- Consumer
- Widget listening to state
- themeMode
- Active theme selection
Next lesson: Summary - Design system