Sub topic 10
Letting users switch between light, dark and system
This chapter assumes you can read the theme, darkTheme and themeMode arguments of MaterialApp. It also assumes you know how to build a light and a dark ColorScheme from one seed color, and that you are comfortable with ChangeNotifier or ValueNotifier. Here you will add a runtime switch so users can choose Light, Dark or System. Saving that choice across launches is covered in the next chapter.
What the switch changes
Switching themes at runtime means changing one value: the themeMode passed to MaterialApp. The two ThemeData objects stay the same. MaterialApp picks which one to use.
ThemeMode has three values:
| Value | Theme used | Follows the device? |
|---|---|---|
| `ThemeMode.light` | `theme` | No |
| `ThemeMode.dark` | `darkTheme` | No |
| `ThemeMode.system` | `theme` or `darkTheme`, based on platform brightness | Yes |
With ThemeMode.system, MaterialApp reads the platform brightness from MediaQuery. If the user changes the device setting while your app is running, the app switches by itself. You write no listener for that.
If you set themeMode: ThemeMode.dark but leave darkTheme as null, Flutter falls back to theme. The app stays light, and no error is reported. Always provide both themes when you offer a switch.
A minimal switcher with ValueNotifier
The smallest setup is a ValueNotifier<ThemeMode> that lives outside the widget tree. A ValueListenableBuilder wraps MaterialApp, so a new mode rebuilds the app with the new themeMode.
import 'package:flutter/material.dart';
final ValueNotifier<ThemeMode> themeModeNotifier =
ValueNotifier(ThemeMode.system);
void main() => runApp(const App());
class App extends StatelessWidget {
const App({super.key});
static const _seed = Color(0xFF6750A4);
static final _light = ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: _seed),
);
static final _dark = ThemeData(
colorScheme: ColorScheme.fromSeed(
seedColor: _seed,
brightness: Brightness.dark,
),
);
@override
Widget build(BuildContext context) {
return ValueListenableBuilder<ThemeMode>(
valueListenable: themeModeNotifier,
builder: (context, mode, _) {
return MaterialApp(
theme: _light,
darkTheme: _dark,
themeMode: mode,
home: const SettingsPage(),
);
},
);
}
}
class SettingsPage extends StatelessWidget {
const SettingsPage({super.key});
@override
Widget build(BuildContext context) {
final brightness = Theme.of(context).brightness;
return Scaffold(
appBar: AppBar(title: const Text('Settings')),
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
ValueListenableBuilder<ThemeMode>(
valueListenable: themeModeNotifier,
builder: (context, mode, _) {
return SegmentedButton<ThemeMode>(
segments: const [
ButtonSegment(
value: ThemeMode.light,
label: Text('Light'),
icon: Icon(Icons.light_mode),
),
ButtonSegment(
value: ThemeMode.system,
label: Text('System'),
icon: Icon(Icons.brightness_auto),
),
ButtonSegment(
value: ThemeMode.dark,
label: Text('Dark'),
icon: Icon(Icons.dark_mode),
),
],
selected: {mode},
onSelectionChanged: (selection) {
themeModeNotifier.value = selection.first;
},
);
},
),
const SizedBox(height: 16),
Text('Active brightness: ${brightness.name}'),
],
),
),
);
}
}Two details in this code matter in real apps.
Hoist the ThemeData objects
The ThemeData objects are static final fields, not built inside builder. Building them inside builder creates new objects on every rebuild. That is wasteful, and it can restart theme animations on rebuilds that have nothing to do with the theme. Create them once and reuse them.
The selection must listen too
The SegmentedButton sits inside its own ValueListenableBuilder. Many first attempts read themeModeNotifier.value directly in build, and the highlighted segment then fails to move.
The cause is const SettingsPage(). When MaterialApp rebuilds, it receives the same const widget instance. Flutter sees an identical widget and skips calling its build. The new theme still reaches descendants through Theme, but only widgets that depend on it get rebuilt. Your read of .value is not a dependency, so the selection goes stale.
The rule: any widget that displays the current mode must listen to the notifier itself. Do not count on the MaterialApp rebuild to refresh it.
Moving to a controller class
A bare global notifier is fine for a demo. In a larger app, a small controller class gives you one place for rules, such as ignoring repeated values. It is also where persistence will go in the next chapter.
import 'package:flutter/material.dart';
class ThemeController extends ChangeNotifier {
ThemeController([ThemeMode initial = ThemeMode.system]) : _mode = initial;
ThemeMode _mode;
ThemeMode get mode => _mode;
void setMode(ThemeMode mode) {
if (mode == _mode) return;
_mode = mode;
notifyListeners();
}
}
final themeController = ThemeController();
void main() => runApp(const ControllerApp());
class ControllerApp extends StatelessWidget {
const ControllerApp({super.key});
static const _seed = Color(0xFF6750A4);
static final _light = ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: _seed),
);
static final _dark = ThemeData(
colorScheme: ColorScheme.fromSeed(
seedColor: _seed,
brightness: Brightness.dark,
),
);
@override
Widget build(BuildContext context) {
return ListenableBuilder(
listenable: themeController,
builder: (context, _) {
return MaterialApp(
theme: _light,
darkTheme: _dark,
themeMode: themeController.mode,
home: const HomePage(),
);
},
);
}
}
class HomePage extends StatelessWidget {
const HomePage({super.key});
@override
Widget build(BuildContext context) {
final isDark = Theme.of(context).brightness == Brightness.dark;
return Scaffold(
appBar: AppBar(
title: const Text('Home'),
actions: [
IconButton(
tooltip: isDark ? 'Switch to light' : 'Switch to dark',
icon: Icon(isDark ? Icons.light_mode : Icons.dark_mode),
onPressed: () {
themeController.setMode(
isDark ? ThemeMode.light : ThemeMode.dark,
);
},
),
],
),
body: const Center(child: Text('Tap the icon in the app bar')),
);
}
}ListenableBuilder works with any Listenable, including a ChangeNotifier. It is available in current stable Flutter, so you do not need AnimatedBuilder as a stand-in.
Designing the control
Offer three choices, not two
A single light/dark toggle is simple but loses information. Once the user taps it, you have replaced "follow my device" with a fixed choice. The three-way control keeps System as an explicit option. Make System the default for first launch, because it respects what the user already told their device.
A quick toggle must resolve System first
The app bar button above decides its direction from Theme.of(context).brightness, which is the active brightness. It does not decide from themeController.mode. If the mode is system and the device is dark, the mode value tells you nothing about what the user sees. Reading the active brightness makes the button correct in all three states. You can also use MediaQuery.platformBrightnessOf(context) if you need the device value regardless of the app's choice.
Labels and icons
Segments with icons and text are easier to scan than icons alone. For the quick toggle, set a tooltip, which also becomes the accessibility label for screen readers. Keep the tooltip describing the action ("Switch to light"), not the current state.
Animation behavior
MaterialApp wraps its theme in an AnimatedTheme. When themeMode changes, colors and many other properties interpolate over themeAnimationDuration, which defaults to 200 ms. Two knobs are available:
themeAnimationDurationchanges the length. UseDuration.zeroto switch instantly.themeAnimationCurvechanges the easing.
Interpolation uses each ThemeData's lerp. This is also why custom theme extensions must implement lerp, which a later chapter covers.
Edge cases and common errors
- Selection does not update. See the const widget issue above. Wrap the control in its own listener.
- Switch has no visible effect. Check that
darkThemeis set. Check that the widgets you expect to change read colors fromTheme.of(context)and not from hard-codedColors.whiteorColors.black. - Whole app state resets. Do not create the
ThemeControllerinside thebuildmethod of a widget that rebuilds. Each rebuild would make a fresh controller set to System. Keep it in a long-lived place: a top-level variable, aStatefield, or a provider scope. - Flash of the wrong theme at launch. If you load a saved mode asynchronously, the first frame uses the default. The persistence chapter shows how to load before
runApp. - Pushed routes look wrong. They are fine. Routes live under
MaterialApp, so they receive the same theme. AThemewidget wrapped around only part of the tree is the usual cause when a subtree does not follow. - Status bar icons. On some platforms the status bar icon brightness comes from the app bar's theme. If icons become unreadable in one mode, set
AppBar.systemOverlayStyleorAppBarTheme.systemOverlayStyleexplicitly.
Testing the switch
A widget test can pump the app, tap a segment, and check the active brightness. The check reads Theme.of(context).brightness from any widget under MaterialApp, for example tester.element(find.byType(Scaffold)). To test System, set the test platform brightness with tester.platformDispatcher.platformBrightnessTestValue = Brightness.dark. Remember to call tester.platformDispatcher.clearAllTestValues() when finished.
Exercise
In the ValueNotifier example, you remove the inner ValueListenableBuilder and write selected: {themeModeNotifier.value} directly inside SettingsPage.build. The app colors still change when you tap Dark, but the Dark segment never looks selected. Why, and what are two ways to fix it?
Show answer
MaterialApp is rebuilt and passes the same const SettingsPage() instance, so Flutter does not call SettingsPage.build again. The theme update reaches widgets that depend on Theme, but the page never depends on the notifier, so the selection value is stale. Fix 1: wrap the SegmentedButton in a ValueListenableBuilder (or ListenableBuilder) on the notifier. Fix 2: make the page non-const or give it its own listener, for example by converting it to a StatefulWidget that calls addListener and setState. The first fix is smaller and rebuilds less.
Exercise
A quick-toggle button must flip the app between light and dark. Why should it read Theme.of(context).brightness and not themeController.mode to decide the new mode?
Show answer
When the mode is ThemeMode.system, the mode value does not say whether the app is currently light or dark. The active brightness does, so the button can always choose the opposite one and set an explicit light or dark mode.