Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 73 ยท Material, styling and assets

Themes, Colors and Dark Mode

Style a whole Flutter app from one place: ThemeData, ColorScheme.fromSeed, TextTheme, component themes, ThemeExtension and a light, dark and system theme switch.

If every button in your app sets its own color, changing the brand color means editing hundreds of places. Flutter solves this with themes. A theme is a bundle of colors, text styles and component styles that sits high in the widget tree. Widgets below it look up what they need, so one change at the top restyles the whole app.

Dark mode comes almost for free with this idea: you provide a second theme, and Flutter picks between them. In this lesson you will build a color scheme from one seed color, style text and components, add your own custom theme values, and let the user switch between light, dark and system. The lookup mechanism itself, Theme.of(context), is explained in BuildContext and InheritedWidget.

Real vs stand-in. The Dart code is real and read-only. The live examples are JavaScript stand-ins: one derives a small light and dark palette from a seed color (the real algorithm is far more sophisticated), and one resolves a theme by the system or user setting.

One theme, many widgets

ColorScheme Roles like primary and surface.
TextTheme Headline, title, body, label.
Component themes Default look for buttons, cards.
ThemeExtension Your own values, like success green.
1 / 2

ThemeData and MaterialApp

You give MaterialApp a theme. Anything you do not set uses a sensible Material 3 default.

DART
void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Recipes',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: const Color(0xFF2E7D32)),
        useMaterial3: true,
      ),
      home: const HomePage(),
    );
  }
}

Material 3 is on by default in current Flutter, so useMaterial3: true is shown for clarity; you can leave it out.

ColorScheme: colors with roles

A ColorScheme is a set of colors named by their job, not by their hue: primary, onPrimary (text or icons drawn on primary), secondary, surface, onSurface, error, onError and more. Widgets ask for a role, so they stay readable when the actual colors change.

ColorScheme.fromSeed makes a whole harmonious scheme from one color. The same seed gives a matching dark scheme when you pass brightness:

DART
final lightScheme = ColorScheme.fromSeed(
  seedColor: const Color(0xFF2E7D32),
);
final darkScheme = ColorScheme.fromSeed(
  seedColor: const Color(0xFF2E7D32),
  brightness: Brightness.dark,
);

Read colors from the theme instead of hard-coding them:

DART
Widget build(BuildContext context) {
  final colors = Theme.of(context).colorScheme;
  return Container(
    color: colors.primaryContainer,
    padding: const EdgeInsets.all(16),
    child: Text(
      'Welcome back',
      style: TextStyle(color: colors.onPrimaryContainer),
    ),
  );
}

Pairs matter: a primaryContainer background goes with onPrimaryContainer text. Mixing a role with the wrong "on" color is how you get low-contrast text. See Accessibility and internationalization for contrast rules.

Stand-in: a seed becomes a palette

The real fromSeed works in a perceptual color space called HCT and produces about 30 roles. This stand-in only rotates lightness in HSL to show the idea: the same seed gives a light set and a dark set where each "on" color contrasts with its background.

JS Seed color to light and dark roles (simplified)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice how primary is dark in the light scheme and light in the dark one, while the matching onPrimary flips the other way. That is the contract widgets rely on.

TextTheme

Instead of typing sizes everywhere, use named text styles. Material 3 has fifteen of them in five groups: display, headline, title, body and label, each in large, medium and small.

DART
final textTheme = Theme.of(context).textTheme;

Column(
  crossAxisAlignment: CrossAxisAlignment.start,
  children: [
    Text('Pasta night', style: textTheme.headlineMedium),
    Text('Ready in 20 minutes', style: textTheme.bodyLarge),
    Text('Vegetarian', style: textTheme.labelSmall),
  ],
)

To change styles app-wide, set textTheme in ThemeData. Use copyWith on a single style to adjust it while keeping the rest (family, spacing):

DART
ThemeData(
  colorScheme: lightScheme,
  textTheme: const TextTheme(
    headlineMedium: TextStyle(fontWeight: FontWeight.w700, letterSpacing: -0.5),
  ),
)

// One-off tweak while keeping the theme's other properties:
Text('Sale', style: textTheme.titleMedium?.copyWith(color: colors.error));

A custom font family goes in fontFamily once the font is declared in your pubspec (Fonts, images and assets).

Component themes

Every Material widget has a theme class: AppBarTheme, FilledButtonThemeData, CardThemeData, InputDecorationTheme and so on. Set them once and every instance follows.

DART
ThemeData(
  colorScheme: lightScheme,
  appBarTheme: const AppBarTheme(centerTitle: true),
  cardTheme: CardThemeData(
    elevation: 0,
    shape: RoundedRectangleBorder(
      borderRadius: BorderRadius.circular(16),
      side: BorderSide(color: lightScheme.outlineVariant),
    ),
  ),
  filledButtonTheme: FilledButtonThemeData(
    style: FilledButton.styleFrom(
      minimumSize: const Size.fromHeight(48),
    ),
  ),
  inputDecorationTheme: const InputDecorationTheme(
    border: OutlineInputBorder(),
  ),
)

The rule of thumb: style one widget with its own style, style all of them with the theme. Class and parameter names in theme data have shifted slightly between Flutter versions (for example CardTheme became CardThemeData), so if the analyzer complains, check the version you installed.

ThemeExtension: your own theme values

What if you need a color Material has no role for, like a "success" green or a spacing scale? ThemeExtension lets you add custom data to ThemeData, with proper copyWith and lerp (interpolation, so theme changes can animate).

DART
@immutable
class AppColors extends ThemeExtension<AppColors> {
  const AppColors({required this.success, required this.warning});

  final Color success;
  final Color warning;

  @override
  AppColors copyWith({Color? success, Color? warning}) =>
      AppColors(success: success ?? this.success, warning: warning ?? this.warning);

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

// Register it:
ThemeData(extensions: const [AppColors(success: Color(0xFF2E7D32), warning: Color(0xFFED6C02))]);

// Use it:
final appColors = Theme.of(context).extension<AppColors>()!;
Icon(Icons.check_circle, color: appColors.success);

Provide a different AppColors in the dark theme, since a green that works on white may glow too much on black.

Dark mode and the theme switch

MaterialApp takes both themes and a themeMode:

DART
MaterialApp(
  theme: ThemeData(colorScheme: lightScheme),
  darkTheme: ThemeData(colorScheme: darkScheme),
  themeMode: ThemeMode.system,   // follow the device; or .light / .dark
  home: const HomePage(),
)

With ThemeMode.system, Flutter checks the device brightness (the platformBrightness you can also read from MediaQuery, see Responsive and adaptive layouts) and switches on its own when the user changes it in system settings.

To offer your own switch, the mode must be state that MaterialApp can see. A small version using a ValueNotifier (covered in Lifting state up and ValueNotifier):

DART
final themeMode = ValueNotifier<ThemeMode>(ThemeMode.system);

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return ValueListenableBuilder<ThemeMode>(
      valueListenable: themeMode,
      builder: (context, mode, _) => MaterialApp(
        theme: ThemeData(colorScheme: lightScheme),
        darkTheme: ThemeData(colorScheme: darkScheme),
        themeMode: mode,
        home: const SettingsPage(),
      ),
    );
  }
}

// In a settings screen:
SegmentedButton<ThemeMode>(
  segments: const [
    ButtonSegment(value: ThemeMode.system, label: Text('System')),
    ButtonSegment(value: ThemeMode.light, label: Text('Light')),
    ButtonSegment(value: ThemeMode.dark, label: Text('Dark')),
  ],
  selected: {themeMode.value},
  onSelectionChanged: (s) => themeMode.value = s.first,
)

To remember the choice between launches, save it with a storage package (Local storage) and read it before runApp.

Stand-in: resolving the active theme

JS How themeMode picks a theme

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice that the device setting only matters in system mode. If you forget to give a darkTheme, Flutter falls back to theme, so dark mode silently does nothing.

Common mistakes

  • Hard-coded colors like Colors.white for a background break in dark mode. Use colorScheme roles.
  • Setting a theme on the wrong side of MaterialApp. Theme.of(context) finds the nearest theme above the context, so a Theme widget you create in build is only visible to its children. Use Builder if you need to read it right there.
  • Forgetting brightness: Brightness.dark in the dark fromSeed, which makes a light scheme in a dark theme.
  • Testing only one mode. Open every screen in both before release.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does ColorScheme.fromSeed produce?

    fromSeed generates a harmonious ColorScheme. Pass brightness: Brightness.dark for the dark version.
  2. 2. Which widget text color goes with a primaryContainer background?

    Each background role has an 'on' partner chosen for contrast. Pair primaryContainer with onPrimaryContainer.
  3. 3. With themeMode: ThemeMode.system, what decides between theme and darkTheme?

    In system mode Flutter follows the platform brightness and switches when the user changes it.
  4. 4. What is ThemeExtension for?

    A ThemeExtension adds typed custom data to the theme, with copyWith and lerp so it can be animated between themes.
  5. 5. You pass only theme (no darkTheme) and the device is in dark mode with ThemeMode.system. What happens?

    Without darkTheme, Flutter uses theme in every brightness.

Summary

  • A theme centralizes colors, text styles and component styles; widgets read it with Theme.of(context).
  • ColorScheme.fromSeed builds a role-based palette; use matching on* colors for readable content.
  • TextTheme gives named styles; component themes set defaults for whole widget families.
  • ThemeExtension adds custom typed values and should be defined for both light and dark.
  • Dark mode needs darkTheme plus themeMode; a user switch needs state above MaterialApp.
  • Avoid hard-coded colors and test every screen in both modes.

Next: Fonts, Images and Assets