Menu
CoddyTech

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 icon

Challenge

Easy

Make the switch flip the theme:

  • in onChanged, store the new value in _dark inside setState
  • set the MaterialApp's themeMode: 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) {},
              ),
            ],
          ),
        ),
      ),
    );
  }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Layout That Fits

Practice on your own: Online Flutter compiler