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
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.
Recommended next exercise
Guided practice and next step
- More Flutter exercises
- C exercises to strengthen fundamentals
- Programming in C in 100 Solved Exercises
- View the C book on Amazon (included in Kindle Unlimited)
- Subscribe to the newsletter
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.