Theme switching
- Flutter course
- Expert
- Lesson 34/39
- 4 min
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(),
),
),
);Practice 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.
Starter code
import 'package:flutter/material.dart';
// ThemeController: ChangeNotifier tabanlı
// isDark: bool, başlangıçta false
// toggle(): değeri tersine çevir ve dinleyicileri uyar
// main: oluştur, toggle çağır, isDark yazdır
void main() {
}Sample 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);
}Expected output
true
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which method of ChangeNotifier notifies listeners about a theme change?
- build
- updateListeners
- notifyListeners Correct answer
- setState
Explanation: notifyListeners reports the change in ChangeNotifier to all listening widgets; Consumer and context.watch listen for this signal.
2 Toggle method
void toggle() {
_mode = (_mode == ThemeMode.light) ? ThemeMode.dark : ____;
notifyListeners();
}
void toggle() {
_mode = (_mode == ThemeMode.light) ? ThemeMode.dark : ThemeMode.light;
notifyListeners();
}
Explanation: toggle switches between light and dark; if dark, it returns to light.
3 Theme switching parts
| Term | Meaning |
|---|---|
ChangeNotifier |
Notifies state changes |
notifyListeners |
Alerts listeners |
Consumer |
Widget listening to state |
themeMode |
Active theme selection |