On this page15 sections
  1. Prerequisites
  2. Connection With Previous Lectures
  3. Learning Objectives
  4. 1. One Function, Two Themes
  5. 2. theme, darkTheme and themeMode
  6. 3. Which Mode Is Showing?
  7. 4. A Button to Switch
  8. Code Examples
  9. Common Beginner Mistakes
  10. Best Practices
  11. Mini Challenge
  12. Practice Questions
  13. Practice Answers
  14. Key Takeaways
  15. Full Code (Copy-Paste Reference)

Lecture 003: Light & Dark Mode

Category1: Theme Basics
Lecture003 of 008
Estimated video length12 min
TargetFlutter 3.44 · Dart 3.12
LevelBeginner

Most phones have a dark mode, and users expect apps to follow it. Flutter lets you give MaterialApp two themes, light and dark, and choose between them with ThemeMode. This lecture adds dark mode to My Notes and a button to switch.

Contents

Prerequisites · Connection · Objectives · Lesson · Code Examples · Common Mistakes · Best Practices · Mini Challenge · Practice Questions · Answers · Takeaways · Full Code


Prerequisites

Lectures 001–002, and StatefulWidget with setState (Essential Widgets).


Connection With Previous Lectures

buildTheme() from Lecture 002 gains a Brightness parameter, so the same function builds both the light and the dark theme.


Learning Objectives

  • Build matching light and dark themes from one function
  • Use theme, darkTheme and themeMode on MaterialApp
  • Explain ThemeMode.system, .light and .dark
  • Switch modes with a button and setState
  • Check which mode is showing with Theme.of(context).brightness

1. One Function, Two Themes

ColorScheme.fromSeed takes a brightness. With Brightness.dark, it builds dark backgrounds and light text from the same seed:

dart
ThemeData buildTheme(Brightness brightness) {
  final colors = ColorScheme.fromSeed(
    seedColor: Colors.teal,
    brightness: brightness,
  );

  return ThemeData(
    colorScheme: colors,
    appBarTheme: AppBarTheme(
      backgroundColor: colors.primary,
      foregroundColor: colors.onPrimary,
    ),
    cardTheme: CardThemeData(
      elevation: 0,
      color: colors.secondaryContainer,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
    ),
  );
}

Because the component themes use colour roles, they automatically look right in both modes.

2. theme, darkTheme and themeMode

dart
MaterialApp(
  theme: buildTheme(Brightness.light),
  darkTheme: buildTheme(Brightness.dark),
  themeMode: ThemeMode.system,
  ...
)
themeModeShows
ThemeMode.systemfollows the phone's setting (the default)
ThemeMode.lightalways theme
ThemeMode.darkalways darkTheme

With just these three lines, My Notes already follows the phone's dark mode.

3. Which Mode Is Showing?

themeMode says what was requested. To know what is actually on screen (important for system), ask the theme:

dart
final isDark = Theme.of(context).brightness == Brightness.dark;

4. A Button to Switch

themeMode is part of MaterialApp, so the widget that builds MaterialApp keeps it in state. HomeScreen gets a callback to change it:

dart
class _NotesAppState extends State<NotesApp> {
  ThemeMode _themeMode = ThemeMode.system;

  void _setDark(bool dark) {
    setState(() {
      _themeMode = dark ? ThemeMode.dark : ThemeMode.light;
    });
  }
  ...
}

The button asks for the opposite of what's showing: onDarkChanged(!isDark).


Code Examples

Example 1: My Notes With Dark Mode

lib/main.dart

dart
import 'package:flutter/material.dart';

void main() {
  runApp(const NotesApp());
}

ThemeData buildTheme(Brightness brightness) {
  final colors = ColorScheme.fromSeed(
    seedColor: Colors.teal,
    brightness: brightness,
  );

  return ThemeData(
    colorScheme: colors,
    appBarTheme: AppBarTheme(
      backgroundColor: colors.primary,
      foregroundColor: colors.onPrimary,
    ),
    cardTheme: CardThemeData(
      elevation: 0,
      color: colors.secondaryContainer,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
    ),
  );
}

class NotesApp extends StatefulWidget {
  const NotesApp({super.key});

  @override
  State<NotesApp> createState() => _NotesAppState();
}

class _NotesAppState extends State<NotesApp> {
  ThemeMode _themeMode = ThemeMode.system;

  void _setDark(bool dark) {
    setState(() {
      _themeMode = dark ? ThemeMode.dark : ThemeMode.light;
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'My Notes',
      debugShowCheckedModeBanner: false,
      theme: buildTheme(Brightness.light),
      darkTheme: buildTheme(Brightness.dark),
      themeMode: _themeMode,
      home: HomeScreen(onDarkChanged: _setDark),
    );
  }
}

class HomeScreen extends StatelessWidget {
  const HomeScreen({super.key, required this.onDarkChanged});

  final ValueChanged<bool> onDarkChanged;

  @override
  Widget build(BuildContext context) {
    final isDark = Theme.of(context).brightness == Brightness.dark;

    return Scaffold(
      appBar: AppBar(
        title: const Text('My Notes'),
        actions: [
          IconButton(
            tooltip: 'Toggle theme',
            icon: Icon(isDark ? Icons.light_mode : Icons.dark_mode),
            onPressed: () => onDarkChanged(!isDark),
          ),
        ],
      ),
      body: const Padding(
        padding: EdgeInsets.all(16),
        child: Card(
          child: Padding(
            padding: EdgeInsets.all(16),
            child: Text('Buy milk and bread'),
          ),
        ),
      ),
    );
  }
}

What you'll see: the app starts in the phone's mode. Tap the sun/moon button and the whole app switches, with a smooth colour animation. The icon shows the mode you'd switch to.

ValueChanged<bool> is Flutter's name for void Function(bool): a callback that receives a value.


Common Beginner Mistakes

1. Toggling the stored mode instead of what's showing

dart
_themeMode = _themeMode == ThemeMode.dark ? ThemeMode.light : ThemeMode.dark;

It looks right, but on a phone that's already in dark mode the app starts on system, which shows dark. The first tap switches to dark, which looks exactly the same, so the button seems to do nothing. (We tested this: after the first tap the screen was still dark.) Base the switch on Theme.of(context).brightness, as in the example.

2. Forgetting darkTheme: with only theme, ThemeMode.dark has nothing dark to show, so Flutter keeps using your light theme. Dark mode silently does nothing. (We checked: themeMode: ThemeMode.dark with no darkTheme still gave Brightness.light.)

3. Hard-coded colours: any Colors.white or Colors.black in a widget looks wrong in one of the two modes. Use colour roles (colors.surface, colors.onSurface).


Best Practices

  • Build both themes from one function with a Brightness parameter, so they never drift apart.
  • Default to ThemeMode.system: respect the user's phone setting.
  • Test every screen in both modes before shipping.

Mini Challenge

Add a second icon button that sets ThemeMode.system again. Hint: change _setDark into a _setMode(ThemeMode mode) method and pass that down instead.


Practice Questions

  1. Which three MaterialApp properties control light and dark mode?
  2. What does ThemeMode.system do?
  3. How do you know whether the screen is currently dark?
  4. Why does buildTheme take a Brightness?
  5. Why can toggling _themeMode directly make the first tap do nothing?

Practice Answers

  1. theme, darkTheme and themeMode.
  2. It follows the phone's own light/dark setting.
  3. Theme.of(context).brightness == Brightness.dark.
  4. So one function builds both themes from the same seed and component styles.
  5. If the phone is dark, system already shows dark; switching to dark changes nothing visible.

Key Takeaways

  • theme + darkTheme + themeMode give an app light and dark mode.
  • ColorScheme.fromSeed(..., brightness: Brightness.dark) builds the dark palette.
  • ThemeMode.system follows the phone; .light / .dark force a mode.
  • Decide the switch from what's showing, not from the stored mode.
  • Next: setState only works because everything is in one widget. Lecture 004 shows why bigger apps need Provider.

Full Code (Copy-Paste Reference)

Everything the app needs up to and including this lecture. One file so far.

lib/main.dart

dart
import 'package:flutter/material.dart';

void main() {
  runApp(const NotesApp());
}

/// One function builds BOTH themes from the same seed, so they never drift apart.
ThemeData buildTheme(Brightness brightness) {
  final colors = ColorScheme.fromSeed(
    seedColor: Colors.teal,
    brightness: brightness,
  );

  return ThemeData(
    colorScheme: colors,
    appBarTheme: AppBarTheme(
      backgroundColor: colors.primary,
      foregroundColor: colors.onPrimary,
    ),
    cardTheme: CardThemeData(
      elevation: 0,
      color: colors.secondaryContainer,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
    ),
  );
}

class NotesApp extends StatefulWidget {
  const NotesApp({super.key});

  @override
  State<NotesApp> createState() => _NotesAppState();
}

class _NotesAppState extends State<NotesApp> {
  // themeMode lives here because this is the widget that builds MaterialApp.
  ThemeMode _themeMode = ThemeMode.system;

  void _setDark(bool dark) {
    setState(() {
      _themeMode = dark ? ThemeMode.dark : ThemeMode.light;
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'My Notes',
      debugShowCheckedModeBanner: false,
      theme: buildTheme(Brightness.light),
      darkTheme: buildTheme(Brightness.dark),
      themeMode: _themeMode,
      home: HomeScreen(onDarkChanged: _setDark),
    );
  }
}

class HomeScreen extends StatelessWidget {
  const HomeScreen({super.key, required this.onDarkChanged});

  final ValueChanged<bool> onDarkChanged;

  @override
  Widget build(BuildContext context) {
    // What's actually ON SCREEN right now - not just what was requested via themeMode.
    final isDark = Theme.of(context).brightness == Brightness.dark;

    return Scaffold(
      appBar: AppBar(
        title: const Text('My Notes'),
        actions: [
          IconButton(
            tooltip: 'Toggle theme',
            icon: Icon(isDark ? Icons.light_mode : Icons.dark_mode),
            // Always ask for the OPPOSITE of what's showing, never flip a stored flag.
            onPressed: () => onDarkChanged(!isDark),
          ),
        ],
      ),
      body: const Padding(
        padding: EdgeInsets.all(16),
        child: Card(
          child: Padding(
            padding: EdgeInsets.all(16),
            child: Text('Buy milk and bread'),
          ),
        ),
      ),
    );
  }
}