Sub topic 2
ThemeData: the single source of theme values
This chapter assumes you can read basic Dart with null safety, build widget trees, use MaterialApp and Scaffold, and know what a BuildContext is. By the end you will know what ThemeData contains, how it reaches widgets, how to override it for part of the tree, and which mistakes cause surprises.
What ThemeData is
ThemeData is an immutable object that holds every design value Material widgets read: colors, text styles, shapes, spacing density, and the default look of individual components. Widgets do not store their own defaults for these. They ask the nearest theme at build time. Changing one ThemeData therefore changes the whole app, and no widget has to be edited.
The fields you will meet most often fall into a few groups:
| Group | Example fields | What they control |
|---|---|---|
| Color | `colorScheme`, `scaffoldBackgroundColor` | The palette and its named roles |
| Typography | `textTheme`, `primaryTextTheme` | Text styles such as `headlineMedium` and `bodyLarge` |
| Component themes | `appBarTheme`, `filledButtonTheme`, `cardTheme` | Defaults for one widget family |
| Layout feel | `visualDensity`, `materialTapTargetSize` | How compact controls are |
| Platform | `platform`, `pageTransitionsTheme` | Behavior that differs per operating system |
| Custom | `extensions` | Your own tokens (a later chapter covers these) |
| Switches | `useMaterial3`, `brightness` | Which design system and which brightness |
The later chapters of this tutorial each take one of these groups in depth. This chapter is about the container and how it flows through the app.
How a theme reaches widgets
MaterialApp takes a ThemeData through its theme argument and wraps your whole app in a Theme widget. Theme is an InheritedWidget: it publishes its ThemeData to every descendant, and descendants look it up through their BuildContext. A Theme placed deeper in the tree replaces the value for its own subtree only.
Lookup walks up from the widget to the nearest Theme, so the closest one wins. The next chapter covers Theme.of(context) in detail. Here we only need to know that it is how widgets read what ThemeData holds.
Building a ThemeData
You normally create ThemeData through its constructor and pass only the fields you care about. Everything you leave out gets a sensible default.
import 'package:flutter/material.dart';
final ThemeData appTheme = ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: const Color(0xFF6750A4)),
visualDensity: VisualDensity.standard,
appBarTheme: const AppBarTheme(centerTitle: true),
);
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'ThemeData demo',
theme: appTheme,
home: Scaffold(
appBar: AppBar(title: const Text('ThemeData')),
body: const Center(child: Text('One theme, whole app')),
),
);
}
}The theme is a top-level final, not something built inside build. The gotchas section explains why that matters.
ColorScheme.fromSeed is covered in a later chapter. For now, treat it as a way to get a complete, consistent palette from one color.
Defaults and useMaterial3
The useMaterial3 flag selects the design system. In current stable Flutter it defaults to true, so a plain ThemeData() already gives you Material 3 shapes, colors, and typography. Older tutorials set useMaterial3: true explicitly because it used to default to false. That line is now redundant but harmless.
You can still opt out:
final ThemeData legacyTheme = ThemeData(
useMaterial3: false,
primarySwatch: Colors.indigo,
);With useMaterial3: false, widgets switch back to Material 2 defaults, and fields such as primarySwatch matter again. Material 2 support is deprecated and will eventually be removed, so use it only to keep an existing app stable while you migrate.
Brightness belongs to the color scheme
ThemeData has a brightness field, but the brightness that matters in Material 3 is the one stored in the ColorScheme. If you pass a colorScheme and a brightness that disagree, Flutter reports an assertion error in debug mode. Pick one source. The usual choice is to set brightness on the ColorScheme and leave ThemeData.brightness alone. The dark mode chapter shows the pattern.
Overriding the theme for part of the tree
Sometimes one region needs different values: a destructive button, a card with an inverted palette, a dense table. Wrap that region in a Theme widget whose data is a modified copy of the inherited theme.
import 'package:flutter/material.dart';
class DangerZone extends StatelessWidget {
const DangerZone({super.key});
@override
Widget build(BuildContext context) {
final base = Theme.of(context);
final scheme = base.colorScheme;
return Theme(
data: base.copyWith(
colorScheme: scheme.copyWith(
primary: scheme.error,
onPrimary: scheme.onError,
),
),
child: FilledButton(
onPressed: () {},
child: const Text('Delete account'),
),
);
}
}copyWith returns a new ThemeData with the named fields replaced and the rest kept. Starting from Theme.of(context) keeps everything the app already configured, such as fonts, shapes, and component themes. Building a fresh ThemeData(...) inside the subtree would discard all of that and fall back to defaults.
The button here changes color because Material 3 FilledButton reads its background from colorScheme.primary and its label color from colorScheme.onPrimary.
The context trap
A Theme widget only affects its descendants. If you create the Theme and call Theme.of(context) in the same build method, you get the theme from above it, because that context belongs to the parent. When a child needs the new values, put it in its own widget class or wrap it in a Builder:
Theme(
data: Theme.of(context).copyWith(visualDensity: VisualDensity.compact),
child: Builder(
builder: (innerContext) {
final density = Theme.of(innerContext).visualDensity;
return Text('Density: ${density.horizontal}');
},
),
)innerContext sits below the new Theme, so it sees the compact density. The outer context would not.
Theme changes animate
MaterialApp animates between old and new ThemeData values. It uses an AnimatedTheme internally, and the length is set by themeAnimationDuration, which defaults to 200 ms. Each field is interpolated with its own lerp. This is why a theme switch fades smoothly instead of snapping. It is also why custom theme data must define lerp, which the ThemeExtension chapter covers.
If you do not want the transition, set themeAnimationDuration: Duration.zero on MaterialApp.
Gotchas and failure modes
- Building ThemeData inside
build.ThemeDataimplements value equality, so a rebuilt but identical theme usually does not cause extra work. Constructing it on every build still allocates a large object each time, andColorScheme.fromSeedruns a color-generation algorithm. Hoist themes intofinalfields or top-level variables. - Hard-coded colors.
Colors.deepPurpleinside a widget ignores the theme. It will not change in dark mode and will not follow a redesign. Read from the theme instead. - Partial overrides that start from scratch.
Theme(data: ThemeData(...))replaces the entire inherited theme for that subtree. UseTheme.of(context).copyWith(...)unless you really want a reset. - Expecting
copyWithto recompute derived values.copyWithchanges only the fields you name. Values the original constructor derived from other fields are not recomputed. This is a larger concern with Material 2 fields likeprimaryColor. In Material 3, overridecolorSchemeand the component themes, which widgets read directly. - Mixing
useMaterial3: falsewith M3 code. Roles such asprimaryContainerexist onColorSchemeeither way, but legacy widgets do not use them the way M3 widgets do. Results look inconsistent. - Reading the theme in
initState.Theme.of(context)registers a dependency, which is not allowed that early. Read it inbuildordidChangeDependencies.
Putting it together
A good project setup has one file that exposes the app's ThemeData values, imported by MaterialApp and by nothing else. Widgets never import that file. They read the theme through their context. This keeps the theme replaceable: a dark variant, a brand variant, or a test theme can be passed in without touching widget code.
Exercise
A teammate writes Theme(data: ThemeData(colorScheme: ColorScheme.fromSeed(seedColor: Colors.red)), child: MyCard()) to give one card a red palette. After the change, the card's text uses a different font and its corners are square, although the rest of the app uses a custom font and rounded shapes. What went wrong, and how do you fix it?
Show answer
A new ThemeData(...) replaces the whole inherited theme for that subtree, so the app's custom textTheme, shape settings, and component themes are discarded and replaced by defaults. Start from the inherited theme instead: Theme(data: Theme.of(context).copyWith(colorScheme: ColorScheme.fromSeed(seedColor: Colors.red)), child: MyCard()). This keeps every other setting and replaces only the color scheme.
Exercise
Inside one build method you write Theme(data: Theme.of(context).copyWith(visualDensity: VisualDensity.compact), child: Text('${Theme.of(context).visualDensity}')). The text still shows the app's original density. Why, and what are two ways to fix it?
Show answer
The context passed to build belongs to the widget above the new Theme, so Theme.of(context) finds the outer theme. Fix it by wrapping the child in a Builder and using the builder's inner context, or by moving the child into its own widget class so that its build receives a context below the Theme.