Dark Mode in Flutter with ThemeMode: solved exercise

  2 minutes

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

Build a screen with:

  • toggle between light and dark themes
  • apply app-wide ThemeMode
  • keep UI consistent across screens
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),
          ),
        ),
      ),
    );
  }
}

Theme changes are immediate and predictable across the app.

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

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

Yes, for most projects it is the correct baseline.

Yes. It improves user experience significantly.

It can, if contrast and readability are properly handled.