Sub topic 2
Building a palette with ColorScheme.fromSeed
This chapter assumes you know Dart null safety, can build a MaterialApp with a Scaffold, and understand BuildContext. Current Flutter uses Material 3 by default, so ThemeData produces Material 3 color roles without extra flags.
Building a palette with ColorScheme.fromSeed
ColorScheme.fromSeed takes one seed color and generates a full set of color roles: primary, secondary, surface, error, and the matching on colors that sit on top of them. The generated roles are tuned to work together, so you rarely pick each one by hand.
import 'package:flutter/material.dart';
void main() {
const seed = Color(0xFF6750A4);
final scheme = ColorScheme.fromSeed(seedColor: seed);
print(scheme.primary);
print(scheme.onPrimary);
}Creating the dark color scheme
Pass brightness: Brightness.dark with the same seed to get a dark scheme. The hue stays the same, but the tones change so that text and icons keep enough contrast on dark surfaces.
final darkScheme = ColorScheme.fromSeed(
seedColor: const Color(0xFF6750A4),
brightness: Brightness.dark,
);> Do not invert the light colors by hand. Generate the dark scheme from the seed so Material chooses tones that fit a dark background.
Wiring theme, darkTheme and themeMode
MaterialApp takes two themes. theme applies in light mode, and darkTheme applies in dark mode. themeMode decides which one is active.
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
const seed = Color(0xFF6750A4);
return MaterialApp(
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: seed),
),
darkTheme: ThemeData(
colorScheme: ColorScheme.fromSeed(
seedColor: seed,
brightness: Brightness.dark,
),
),
themeMode: ThemeMode.system,
home: const Scaffold(
body: Center(child: Text('Hello, theme')),
),
);
}
}| themeMode value | Active theme |
|---|---|
| ThemeMode.light | theme, always |
| ThemeMode.dark | darkTheme, always |
| ThemeMode.system | Follows the device setting |
Exercise
If the device is set to dark mode and themeMode is ThemeMode.light, which theme does the app use, and why?
Show answer
The app uses theme, the light theme. ThemeMode.light forces the light theme regardless of the device setting, so darkTheme is ignored.