A Dark Mode Switch
Part of the Layout That Fits section of Coddy's Flutter journey. Lesson 25 of 30.
Some people want dark mode in one app and not in the others. Give them a switch.
themeMode: is a setting like any other, so it can come from state. Keep a bool in the State of MyApp, the widget that builds the MaterialApp, and choose the mode from it:
bool _dark = false;
MaterialApp(
themeMode: _dark ? ThemeMode.dark : ThemeMode.light,
...
)When the switch changes _dark inside setState, build runs again, the MaterialApp gets the new mode, and every screen switches theme at once, with a short fade.
The state has to live above MaterialApp, because that is where the theme is chosen. That is why MyApp is a StatefulWidget here.
Challenge
EasyMake the switch flip the theme:
- in
onChanged, store the new value in_darkinsidesetState - set the
MaterialApp'sthemeMode:from_dark: dark when it is true, light when it is false
Try it yourself
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
bool _dark = false;
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.indigo),
),
darkTheme: ThemeData(
colorScheme: ColorScheme.fromSeed(
seedColor: Colors.indigo,
brightness: Brightness.dark,
),
),
home: Scaffold(
appBar: AppBar(title: const Text('Night Reader')),
body: Center(
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
const Text('Dark mode', style: TextStyle(fontSize: 20)),
const SizedBox(width: 12),
Switch(
value: _dark,
onChanged: (value) {},
),
],
),
),
),
);
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Layout That Fits
1Sharing a Row
Expanded Fills the RowSharing Space With flexFlexible Hugs Its ChildSpacer Pushes Apart6Themes and Dark Mode
An App Theme From a SeedTheme.of(context) ColorsText Styles From the ThemeA Dark ThemeA Dark Mode SwitchPractice on your own: Online Flutter compiler