Dark mode helps reduce eye strain in low light and saves battery on devices with OLED screens.
0
0
Dark mode support in Flutter
Introduction
When you want your app to look good in both bright and dark environments.
When users prefer dark mode to reduce glare at night.
To follow system-wide dark mode settings automatically.
To improve battery life on devices with OLED or AMOLED screens.
Syntax
Flutter
MaterialApp( theme: ThemeData.light(), darkTheme: ThemeData.dark(), themeMode: ThemeMode.system, home: MyHomePage(), )
theme sets the light mode style.
darkTheme sets the dark mode style.
themeMode controls which theme is active: light, dark, or system default.
Examples
This forces the app to always use dark mode.
Flutter
MaterialApp( theme: ThemeData.light(), darkTheme: ThemeData.dark(), themeMode: ThemeMode.dark, home: MyHomePage(), )
This forces the app to always use light mode.
Flutter
MaterialApp( theme: ThemeData.light(), darkTheme: ThemeData.dark(), themeMode: ThemeMode.light, home: MyHomePage(), )
This uses custom colors for light and dark themes and follows system settings.
Flutter
MaterialApp(
theme: ThemeData(
primarySwatch: Colors.blue,
brightness: Brightness.light,
),
darkTheme: ThemeData(
primarySwatch: Colors.blue,
brightness: Brightness.dark,
),
themeMode: ThemeMode.system,
home: MyHomePage(),
)Sample App
This app automatically switches between light and dark themes based on the device setting. The text and background colors adjust accordingly.
Flutter
import 'package:flutter/material.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: 'Dark Mode Demo', theme: ThemeData( primarySwatch: Colors.blue, brightness: Brightness.light, ), darkTheme: ThemeData( primarySwatch: Colors.blue, brightness: Brightness.dark, ), themeMode: ThemeMode.system, home: const MyHomePage(), ); } } class MyHomePage extends StatelessWidget { const MyHomePage({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Dark Mode Support'), ), body: const Center( child: Text('Switch your device theme to see changes!'), ), ); } }
OutputSuccess
Important Notes
Use ThemeMode.system to respect the user's device theme preference.
You can customize colors in ThemeData for a unique look in dark mode.
Test your app in both modes to ensure good readability and contrast.
Summary
Dark mode reduces eye strain and saves battery on some devices.
Use theme, darkTheme, and themeMode in MaterialApp to support dark mode.
Test your app in both light and dark modes for best user experience.