Dark Mode in Flutter with ThemeMode: solved exercise

Dark Mode in Flutter with ThemeMode: solved exercise

If you are looking for dark mode in Flutter, this solved exercise gives you a practical implementation pattern you can reuse in real projects.

Problem statement

Build a screen with:

  • toggle between light and dark themes
  • apply app-wide ThemeMode
  • keep UI consistent across screens

Flutter solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import 'package:flutter/material.dart';

void main() => runApp(const ThemeApp());

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

  @override
  State<ThemeApp> createState() => _ThemeAppState();
}

class _ThemeAppState extends State<ThemeApp> {
  bool isDark = false;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.light(),
      darkTheme: ThemeData.dark(),
      themeMode: isDark ? ThemeMode.dark : ThemeMode.light,
      home: Scaffold(
        appBar: AppBar(title: const Text('Dark mode')),
        body: Center(
          child: SwitchListTile(
            value: isDark,
            title: const Text('Dark mode'),
            onChanged: (value) => setState(() => isDark = value),
          ),
        ),
      ),
    );
  }
}

Expected result

Theme changes are immediate and predictable across the app.

Common mistakes

  • Defining only light theme.
  • Hardcoding colors without theme tokens.
  • Not persisting user preference.

Practical use

Dark mode improves long-session UX and is expected in many modern apps.

Guided practice and next step

FAQ

Is ThemeMode enough for dark mode?

Yes, for most projects it is the correct baseline.

Should I persist theme preference?

Yes. It improves user experience significantly.

Does dark mode help accessibility?

It can, if contrast and readability are properly handled.