Sub topic 3
Reading theme values with Theme.of(context)
This chapter assumes you know basic Dart and null safety, how to build widget trees, what BuildContext is, and how MaterialApp and Scaffold fit together. You should also have seen ThemeData and ColorScheme.fromSeed in the previous chapters. Here the focus is on how widgets read the theme, and on the mistakes that make a theme look right in light mode and wrong in dark mode.
What Theme.of actually does
Theme.of(context) returns the ThemeData that applies at that point in the widget tree. It does this through Flutter's inherited-widget mechanism. MaterialApp inserts a Theme widget above your home widget. That Theme widget holds the ThemeData chosen from theme, darkTheme and themeMode. When you call Theme.of(context), Flutter walks up from context until it finds the closest Theme ancestor and returns its data.
Two consequences follow from this:
- The answer depends on where
contextsits in the tree. A differentThemecloser to your widget wins over the one fromMaterialApp. - The call registers your widget as a dependent of that
Theme. When the theme changes, for example when the user switches to dark mode, Flutter rebuilds every dependent widget. You get dark-mode updates without writing any listener code.
The basic pattern
The usual approach is to read the theme once at the top of build, then take colors and text styles from it:
import 'package:flutter/material.dart';
class ThemedCard extends StatelessWidget {
const ThemedCard({super.key});
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final colors = theme.colorScheme;
return Container(
padding: const EdgeInsets.all(16),
color: colors.primaryContainer,
child: Text(
'Headline',
style: theme.textTheme.headlineMedium?.copyWith(
color: colors.onPrimaryContainer,
),
),
);
}
}A few details are worth noting:
primaryContainerandonPrimaryContainerare a matched pair. The "on" color is designed to be readable on top of its partner. Keep pairs together instead of mixing roles.- Text styles on
TextThemeare nullable (TextStyle?). That is why the code uses?.copyWith(...). If you pass the result to a parameter that needs a non-null style, handle the null case or use!only when you control the theme. - The widget has no
if (isDark)branch. BothThemeDataobjects define the same roles, so the same code gives correct colors in either brightness.
Why not hard-code colors
Compare these two lines:
// Fragile: fixed white text stays white on a light surface in light mode.
const Text('Total', style: TextStyle(color: Colors.white));
// Adaptive: the role resolves differently in light and dark themes.
Text('Total', style: TextStyle(color: Theme.of(context).colorScheme.onSurface));Colors.white is correct in only one of the two themes. A role such as onSurface is defined in both, so it stays correct when the theme changes. Hard-coded colors also break when you later add dynamic color or a new seed, because the new palette never reaches them.
This does not mean you can never use a literal color. Brand logos, photo overlays and similar fixed elements can use fixed colors. If the color represents a role in your design system, such as "success" or "warning", define it as a token instead (a later chapter covers ThemeExtension).
Reading from the right context
The most common failure is calling Theme.of with a context that is above the Theme you meant to read.
class BrokenApp extends StatelessWidget {
const BrokenApp({super.key});
@override
Widget build(BuildContext context) {
// This context is above MaterialApp, so no app Theme exists yet.
// Flutter returns a fallback theme, not the one declared below.
final primary = Theme.of(context).colorScheme.primary;
return MaterialApp(
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: const Color(0xFF6750A4)),
),
home: Scaffold(
body: Center(
child: Text('Wrong color', style: TextStyle(color: primary)),
),
),
);
}
}The context passed to BrokenApp.build belongs to BrokenApp, whose ancestors do not include the Theme that MaterialApp creates. The value you read is from a fallback theme, and it never changes when the user switches modes. The fix is to move the read into a widget below MaterialApp:
class FixedHome extends StatelessWidget {
const FixedHome({super.key});
@override
Widget build(BuildContext context) {
final primary = Theme.of(context).colorScheme.primary;
return Scaffold(
body: Center(
child: Text('Right color', style: TextStyle(color: primary)),
),
);
}
}The same problem appears one level down. If a single build method creates a Theme widget and also reads Theme.of(context) in the same method, that read sees the outer theme, not the one you just created. Wrap the inner part in a Builder, or split it into its own widget, so that it gets a context below the new Theme.
Overriding the theme for one subtree
The Theme widget lets you change values for a part of the tree. The safe pattern is to start from the current theme and use copyWith, so everything you do not mention stays the same:
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,
),
),
home: const Scaffold(
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
ThemedCard(),
SizedBox(height: 16),
TertiaryAction(),
],
),
),
),
);
}
}
class ThemedCard extends StatelessWidget {
const ThemedCard({super.key});
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final colors = theme.colorScheme;
return Container(
padding: const EdgeInsets.all(16),
color: colors.primaryContainer,
child: Text(
'Headline',
style: theme.textTheme.headlineMedium?.copyWith(
color: colors.onPrimaryContainer,
),
),
);
}
}
class TertiaryAction extends StatelessWidget {
const TertiaryAction({super.key});
@override
Widget build(BuildContext context) {
final base = Theme.of(context);
return Theme(
data: base.copyWith(
colorScheme: base.colorScheme.copyWith(
primary: base.colorScheme.tertiary,
onPrimary: base.colorScheme.onTertiary,
),
),
child: FilledButton(
onPressed: () {},
child: const Text('Tertiary action'),
),
);
}
}Run this on a device or emulator and toggle the system appearance. The card and the button both update, and the button stays in the tertiary color in both modes, because the override is built from whichever theme is active.
Keep local overrides small. Each one is a place where the design can drift from the rest of the app. If you override the same thing in many places, move it into a component theme or an extension instead.
Reading the theme outside build
Theme.of creates a dependency, and Flutter only allows that at certain times. Calling it in initState fails, because the element is not yet fully attached to the tree. Use didChangeDependencies, which Flutter calls after initState and again whenever a dependency changes:
import 'package:flutter/material.dart';
class ThemeAwareBox extends StatefulWidget {
const ThemeAwareBox({super.key});
@override
State<ThemeAwareBox> createState() => _ThemeAwareBoxState();
}
class _ThemeAwareBoxState extends State<ThemeAwareBox> {
late Color _background;
@override
void didChangeDependencies() {
super.didChangeDependencies();
_background = Theme.of(context).colorScheme.secondaryContainer;
}
@override
Widget build(BuildContext context) {
return SizedBox(
width: 80,
height: 80,
child: ColoredBox(color: _background),
);
}
}In most widgets you can skip this and read directly in build, which is simpler. Use didChangeDependencies only when you derive state from the theme, for example to build an animation tween.
Also avoid reading the theme in an event handler and storing it in a long-lived field. A stored value goes stale after the next theme change. Read it again each time you need it.
Theme brightness and device brightness are different
These two values are easy to confuse:
| Expression | What it tells you |
|---|---|
| `Theme.of(context).brightness` | Brightness of the theme currently applied at this point in the tree |
| `MediaQuery.platformBrightnessOf(context)` | The device's appearance setting, whatever your app chose |
If the user picks "Dark" inside your app while the device is set to light, the first value is Brightness.dark and the second is Brightness.light. For drawing decisions, such as choosing between a light and a dark logo, use the theme value. Use the platform value only when you specifically need to know the device setting.
Cost and rebuilds
A theme lookup is cheap. It is a hash-table lookup on the element's inherited-widget map, not a tree walk, so calling Theme.of(context) several times in one build is fine. Caching it in a local final theme is a readability choice.
What matters more is the rebuild scope. When the theme changes, every widget that called Theme.of (or a theme-reading widget such as Text with default style, Material, Icon) rebuilds. A const child does not skip this if it depends on the theme internally. That is expected, and it is why a mode switch repaints the whole screen. If a screen is expensive to rebuild, look for work inside build that should be cached, not for ways to avoid reading the theme.
Common errors at a glance
- Reading above MaterialApp. The value comes from a fallback theme. Move the read below
MaterialApp. - Reading in the same build that creates the
Theme. UseBuilderor a separate widget. - Calling
Theme.ofininitState. Move it todidChangeDependenciesorbuild. - Hard-coded
Colors.*for role colors. UsecolorSchemeroles. - Mixing unmatched pairs, such as
primaryContainerwithonPrimary. Use the matching "on" role. - Confusing theme brightness with platform brightness. Pick the one that matches your intent.
Exercise
A screen's build method returns Theme(data: ThemeData(colorScheme: ColorScheme.fromSeed(seedColor: Colors.teal)), child: Text('Hi', style: TextStyle(color: Theme.of(context).colorScheme.primary))). The text does not use the teal color. Why, and how do you fix it?
Show answer
The Theme.of(context) call uses the context of the method that creates the Theme, which is above the new Theme, so it reads the outer (app) theme. Fix it by wrapping the Text in a Builder (or moving it to its own widget) so that its context is below the new Theme, or by reading the color from the ColorScheme you just built.
Exercise
The user selects "Dark" in your app's settings while the device is set to light. What do Theme.of(context).brightness and MediaQuery.platformBrightnessOf(context) return, and which one should decide which logo asset to show?
Show answer
Theme.of(context).brightness returns Brightness.dark and MediaQuery.platformBrightnessOf(context) returns Brightness.light. Use the theme brightness to choose the logo, because it reflects what the app is actually showing.