Back to Articles

Beginner

Dark Mode / Theme Management in Flutter

· 6 min read

Dark Mode / Theme Management in Flutter

theme, darkTheme, and themeMode

MaterialApp exposes theme management through three parameters: theme for light mode, darkTheme for dark mode, and themeMode for which one is actually used. ThemeMode.system is the default and automatically follows the device's system setting — when the user switches their phone's theme, the app follows instantly.

MaterialApp(
  theme: ThemeData.light(useMaterial3: true),
  darkTheme: ThemeData.dark(useMaterial3: true),
  themeMode: ThemeMode.system, // follows the device setting
  home: const HomePage(),
)
A settings card transitioning between light and dark color palettes
Colors animating between light and dark as the ThemeMode changes.

Switching the Theme at Runtime

If you want to offer an in-app light/dark/system switch, themeMode can't be a fixed value anymore — it needs to live in some state management solution (ChangeNotifier, Provider, Riverpod, etc.) that rebuilds MaterialApp when it changes.

class ThemeModeController extends ChangeNotifier {
  ThemeMode _mode = ThemeMode.system;
  ThemeMode get mode => _mode;

  void setMode(ThemeMode mode) {
    _mode = mode;
    notifyListeners();
  }
}

// main.dart
ChangeNotifierProvider(
  create: (_) => ThemeModeController(),
  child: Consumer<ThemeModeController>(
    builder: (context, controller, _) => MaterialApp(
      theme: ThemeData.light(useMaterial3: true),
      darkTheme: ThemeData.dark(useMaterial3: true),
      themeMode: controller.mode,
      home: const HomePage(),
    ),
  ),
)

Persisting the User's Choice

A theme preference isn't sensitive data, so SharedPreferences is a fine place for it (always keep actual secrets like tokens or passwords in secure storage instead). Read the saved preference and hand it to the controller every time the app starts.

const _kThemeModeKey = 'theme_mode';

Future<void> saveThemeMode(ThemeMode mode) async {
  final prefs = await SharedPreferences.getInstance();
  await prefs.setString(_kThemeModeKey, mode.name);
}

Future<ThemeMode> loadThemeMode() async {
  final prefs = await SharedPreferences.getInstance();
  final value = prefs.getString(_kThemeModeKey);
  return ThemeMode.values.firstWhere(
    (m) => m.name == value,
    orElse: () => ThemeMode.system,
  );
}

Listening to System Brightness

When themeMode is left at ThemeMode.system, Flutter handles the light/dark switch for you — but sometimes a widget needs to show a different icon or content based on the current brightness. Use MediaQuery.platformBrightnessOf(context) for that; the widget rebuilds automatically whenever the system setting changes.

@override
Widget build(BuildContext context) {
  final brightness = MediaQuery.platformBrightnessOf(context);
  final isDark = brightness == Brightness.dark;
  return Icon(isDark ? Icons.dark_mode : Icons.light_mode);
}

Accessing Colors via Theme.of(context)

Using fixed colors like Colors.black or Colors.white directly is the most common reason a UI breaks in dark mode. Use the colors from Theme.of(context).colorScheme instead; they change automatically based on theme and darkTheme.

// Avoid:
Container(color: Colors.black)

// Prefer:
Container(color: Theme.of(context).colorScheme.surface)
Text(
  'Title',
  style: TextStyle(color: Theme.of(context).colorScheme.onSurface),
)

Custom Colors with ThemeExtension

If you have brand colors that don't have a counterpart in ColorScheme — a 'success' or 'warning' color, say — you can make them part of the theme system with ThemeExtension<T> instead of defining them as separate constants everywhere. That way they also animate smoothly (via lerp) during light/dark transitions.

class BrandColors extends ThemeExtension<BrandColors> {
  const BrandColors({required this.success, required this.warning});

  final Color success;
  final Color warning;

  @override
  BrandColors copyWith({Color? success, Color? warning}) {
    return BrandColors(
      success: success ?? this.success,
      warning: warning ?? this.warning,
    );
  }

  @override
  BrandColors lerp(ThemeExtension<BrandColors>? other, double t) {
    if (other is! BrandColors) return this;
    return BrandColors(
      success: Color.lerp(success, other.success, t)!,
      warning: Color.lerp(warning, other.warning, t)!,
    );
  }
}

final lightTheme = ThemeData.light(useMaterial3: true).copyWith(
  extensions: const [BrandColors(success: Color(0xFF2E7D32), warning: Color(0xFFF9A825))],
);

// Usage
final brand = Theme.of(context).extension<BrandColors>()!;
Icon(Icons.check_circle, color: brand.success);

Things to Watch Out For

1. Theme.of(context) Gives Fresh Data on Every build

Theme is built on an InheritedWidget, so every widget that depends on it rebuilds automatically when the theme changes. Always read it inside build with Theme.of(context) rather than caching it in a field from initState, or your widget won't update when the theme does.

2. Partial Customization with copyWith

Trying to write every field of ThemeData from scratch is long and error-prone. Use ThemeData.light(useMaterial3: true).copyWith(...) and only specify the fields you actually want to change, keeping the rest of Material 3's defaults intact.

Conclusion

Dark mode support starts with MaterialApp's theme/darkTheme/themeMode trio. Persist the user's preference in SharedPreferences, always read colors through Theme.of(context).colorScheme, and keep brand colors inside the theme system with ThemeExtension instead of stepping outside of it.