Sub topic 9
Customizing components with component themes
This chapter assumes you can already build a ThemeData with ColorScheme.fromSeed, wire theme, darkTheme and themeMode on MaterialApp, and read values with Theme.of(context). The earlier chapters cover those. Here we change how individual widgets such as buttons, app bars, cards and text fields look across the whole app.
What a component theme is
A component theme is a property on ThemeData that holds default settings for one kind of widget. appBarTheme configures every AppBar. filledButtonTheme configures every FilledButton. cardTheme configures every Card.
Without component themes, you would style each widget where you create it. That leads to copied code and screens that slowly drift apart. With them, you state the look once and every instance picks it up.
Material 3 widgets already have defaults. Those defaults are computed from your ColorScheme, so a FilledButton uses primary and onPrimary without any setup. A component theme overrides only the properties you set. Everything else keeps the Material 3 default.
The order of precedence
When a widget decides how to draw itself, it checks three sources, from highest to lowest priority:
- Arguments on the widget itself, such as
FilledButton(style: ...). - The nearest component theme in the widget tree.
- The Material 3 defaults, derived from the
ColorScheme.
The merge happens property by property. If a component theme sets the shape and a widget sets only the background color, the button gets both.
Setting the basics
The first example from the plan sets an AppBar default and a FilledButton default:
final lightTheme = ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: const Color(0xFF6750A4)),
appBarTheme: const AppBarTheme(centerTitle: true),
filledButtonTheme: FilledButtonThemeData(
style: FilledButton.styleFrom(
minimumSize: const Size(120, 48),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
),
),
);Button themes take a ButtonStyle, and FilledButton.styleFrom is a convenient way to build one. The call above sets size and shape and leaves colors alone. The colors therefore keep following the ColorScheme, so they change correctly in dark mode.
Do not hard-code colors in a component theme
The most common mistake is to write backgroundColor: Colors.deepPurple inside a component theme. That color is the same in light and dark mode, so the widget stops adapting. It also ignores a dynamic color scheme.
Take colors from the scheme instead. The scheme differs between light and dark, so the component theme follows along.
The cleanest way to do this is a function that builds one ThemeData per brightness. The component themes are written once and read from the scheme that was just created:
import 'package:flutter/material.dart';
ThemeData buildTheme(Brightness brightness) {
final scheme = ColorScheme.fromSeed(
seedColor: const Color(0xFF6750A4),
brightness: brightness,
);
return ThemeData(
colorScheme: scheme,
appBarTheme: const AppBarTheme(centerTitle: true),
filledButtonTheme: FilledButtonThemeData(
style: FilledButton.styleFrom(
minimumSize: const Size(120, 48),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
),
),
cardTheme: CardThemeData(
elevation: 0,
color: scheme.surfaceContainerLow,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
side: BorderSide(color: scheme.outlineVariant),
),
),
inputDecorationTheme: InputDecorationTheme(
filled: true,
fillColor: scheme.surfaceContainerHighest,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide: BorderSide.none,
),
),
);
}
void main() => runApp(const DemoApp());
class DemoApp extends StatelessWidget {
const DemoApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Component themes',
theme: buildTheme(Brightness.light),
darkTheme: buildTheme(Brightness.dark),
themeMode: ThemeMode.system,
home: const DemoPage(),
);
}
}
class DemoPage extends StatelessWidget {
const DemoPage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Components')),
body: const Padding(
padding: EdgeInsets.all(16),
child: Card(
child: Padding(
padding: EdgeInsets.all(16),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
TextField(decoration: InputDecoration(labelText: 'Name')),
SizedBox(height: 16),
FilledButton(onPressed: null, child: Text('Disabled')),
SizedBox(height: 8),
FilledButton(onPressed: _noop, child: Text('Save')),
],
),
),
),
),
);
}
}
void _noop() {}Run it and switch your device between light and dark. The card border, the text field fill and the button colors all change, although the code never mentions a mode.
Which component themes exist
Almost every Material widget has one. These are the ones you will use most:
| Widget | `ThemeData` property | Typical settings |
|---|---|---|
| `AppBar` | `appBarTheme` | `centerTitle`, `elevation`, `backgroundColor` |
| `FilledButton` | `filledButtonTheme` | `ButtonStyle`: size, shape, padding |
| `OutlinedButton` | `outlinedButtonTheme` | `ButtonStyle`: side, shape |
| `TextButton` | `textButtonTheme` | `ButtonStyle` |
| `Card` | `cardTheme` | `elevation`, `shape`, `margin` |
| `TextField` | `inputDecorationTheme` | `filled`, `border`, `contentPadding` |
| `NavigationBar` | `navigationBarTheme` | `indicatorColor`, `labelTextStyle` |
| `SnackBar` | `snackBarTheme` | `behavior`, `shape` |
The ElevatedButton and FilledButton.tonal variants also take their defaults from theme properties (elevatedButtonTheme, and filledButtonTheme for the tonal variant). Check the API docs for the exact property name before you guess.
States: styling a button that is disabled, hovered or pressed
A ButtonStyle stores most properties as a WidgetStateProperty<T>. This is a value that depends on the widget's current states, such as disabled, hovered, pressed and focused. styleFrom hides this for simple cases. When you need state-dependent values, build the property yourself with WidgetStateProperty.resolveWith:
import 'package:flutter/material.dart';
FilledButtonThemeData stateAwareButtons(ColorScheme scheme) {
return FilledButtonThemeData(
style: ButtonStyle(
backgroundColor: WidgetStateProperty.resolveWith((states) {
if (states.contains(WidgetState.disabled)) {
return scheme.onSurface.withValues(alpha: 0.12);
}
if (states.contains(WidgetState.pressed)) {
return scheme.primary.withValues(alpha: 0.85);
}
return scheme.primary;
}),
foregroundColor: WidgetStateProperty.resolveWith((states) {
if (states.contains(WidgetState.disabled)) {
return scheme.onSurface.withValues(alpha: 0.38);
}
return scheme.onPrimary;
}),
),
);
}Returning null from the callback means "no opinion", so the Material 3 default is used for that state. This lets you override only the states you care about. If a state returns a concrete color, you take responsibility for that state in every mode, including hover and focus feedback. Avoid overriding more states than you need.
Overriding for one subtree
Sometimes one screen or one region needs a different look. Wrap that region in a Theme widget built from the current theme with copyWith. Do not start from a fresh ThemeData, which would discard the color scheme and everything else:
Theme(
data: Theme.of(context).copyWith(
filledButtonTheme: FilledButtonThemeData(
style: FilledButton.styleFrom(
backgroundColor: Theme.of(context).colorScheme.error,
foregroundColor: Theme.of(context).colorScheme.onError,
),
),
),
child: FilledButton(
onPressed: () {},
child: const Text('Delete account'),
),
)This turns the button into a destructive-action button using the error and onError roles, so it stays readable in dark mode. A single widget can also use style: directly. Both approaches sit above the app-wide component theme in the precedence order.
Common errors
- A theme change has no visible effect. The widget probably sets the same property in its own
style, which wins over the theme. Search the widget call for explicitstyle:orcolor:arguments. - The component theme works in light mode only. It contains a literal color. Replace it with a role from
scheme. - A new
Theme(data: ThemeData(...))resets everything below it. UseTheme.of(context).copyWith(...)instead. - You built the theme inside
buildon every frame. CreatingThemeDatais not free, and a new object each time forces dependents to rebuild. Create each theme once, as afinalor a function called whenMaterialAppis built. - The wrong theme class name. See the note about
CardThemeDataabove. - A button theme ignored by a custom widget. Only Material widgets that read their component theme respond to it. A container you painted yourself will not, unless you read the values with
Theme.of(context).
Exercise
Your app has a filledButtonTheme that sets minimumSize to 120 by 48 and a rounded shape. One screen contains FilledButton(style: FilledButton.styleFrom(backgroundColor: Colors.green), ...). What size, shape and color does that button get, and what problem does the hard-coded color cause in dark mode?
Show answer
The button is 120 by 48 with the rounded shape, because style properties merge one by one and the widget only sets the background. The background is green, because the widget's own style outranks the theme and the Material 3 default. The green is the same in light and dark mode, so it ignores the color scheme and may have poor contrast against the dark surfaces. Use a role from Theme.of(context).colorScheme, or a ThemeExtension token, so the color adapts to each mode.
Exercise
Why does buildTheme(Brightness brightness) read colors from a local scheme variable instead of writing the component themes separately for the light and dark ThemeData?
Show answer
The component themes are written once and shared by both modes, so they cannot drift apart. Each call creates a ColorScheme with the requested brightness, so any color read from scheme is correct for that mode automatically.