Sub topic 12
Adding your own tokens with ThemeExtension
ColorScheme and TextTheme cover the roles that Material 3 defines. Most apps also need values Material does not define, such as a "success" green, a warning amber, or a spacing scale. This chapter shows how to store those values in the theme with ThemeExtension, so they follow light and dark mode and animate during theme changes.
It assumes you can build a MaterialApp with theme, darkTheme and themeMode, read values with Theme.of(context), and write basic Dart classes with generics.
Why ColorScheme is not enough
Material 3 gives you roles such as primary, error, surfaceContainer and outline. It has no role for "success". Developers often fill this gap in one of three ways, and each has a cost:
- A global constant like
const successGreen = Color(0xFF2E7D32). It ignores dark mode, so the same green appears on a dark surface with poor contrast. - A
Brightnesscheck in each widget (isDark ? a : b). This scatters theme logic across the app and is easy to forget. - A separate inherited widget. This works but duplicates what
Themealready does, and it does not animate with the theme.
A theme extension stores your values on ThemeData itself. They are then resolved from the nearest Theme, switch with darkTheme, and interpolate when the theme animates.
Anatomy of a ThemeExtension
A theme extension is a class that extends ThemeExtension<T>, where T is the class itself. It must implement two methods:
copyWithreturns a copy with some fields replaced.lerpreturns a value between this instance and another one. Thetargument runs from 0.0 to 1.0.
import 'package:flutter/material.dart';
@immutable
class BrandColors extends ThemeExtension<BrandColors> {
const BrandColors({required this.success, required this.onSuccess});
final Color success;
final Color onSuccess;
static const light = BrandColors(
success: Color(0xFF2E7D32),
onSuccess: Colors.white,
);
static const dark = BrandColors(
success: Color(0xFF81C784),
onSuccess: Color(0xFF003910),
);
@override
BrandColors copyWith({Color? success, Color? onSuccess}) {
return BrandColors(
success: success ?? this.success,
onSuccess: onSuccess ?? this.onSuccess,
);
}
@override
BrandColors lerp(ThemeExtension<BrandColors>? other, double t) {
if (other is! BrandColors) return this;
return BrandColors(
success: Color.lerp(success, other.success, t)!,
onSuccess: Color.lerp(onSuccess, other.onSuccess, t)!,
);
}
}Some details in this class matter:
- The class is
@immutableand every field isfinal. Themes are shared and compared, so a mutable extension causes confusing bugs. lightanddarkarestatic constpresets. Defining both next to each other keeps the two palettes easy to compare.lerpreceives a nullableThemeExtension<BrandColors>?. Theother is! BrandColorscheck handlesnulland any wrong type, and returningthismeans "no change".Color.lerpreturnsColor?, because it returnsnullwhen both inputs arenull. The inputs here are non-null, so!is safe.
Registering extensions in both themes
You attach extensions through the extensions parameter of ThemeData. Register one in the light theme and one in the dark theme, using the same type in both:
final lightTheme = ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: const Color(0xFF6750A4)),
extensions: const [BrandColors.light],
);
final darkTheme = ThemeData(
colorScheme: ColorScheme.fromSeed(
seedColor: const Color(0xFF6750A4),
brightness: Brightness.dark,
),
extensions: const [BrandColors.dark],
);ThemeData keeps extensions in a map keyed by their type. You can register many different extension classes, such as BrandColors and Spacing, but only one instance of each type per theme. If you pass two BrandColors instances in the same list, the later one replaces the earlier one.
Reading an extension in a widget
You read an extension with Theme.of(context).extension<T>(). The return type is T?, because the theme might not contain that extension. Calling this on every use gets repetitive, so a small BuildContext extension gives you one place to handle the missing case:
extension BrandThemeContext on BuildContext {
BrandColors get brand =>
Theme.of(this).extension<BrandColors>() ?? BrandColors.light;
}The fallback keeps widgets working in tests that pump a bare MaterialApp with no extensions. If you would rather fail loudly during development, use extension<BrandColors>()! or add an assert. Choose one policy for the whole app.
Here is a complete app that uses the extension through a banner widget:
import 'package:flutter/material.dart';
// BrandColors, BrandThemeContext, lightTheme and darkTheme
// are defined as shown earlier in this chapter.
void main() => runApp(const BrandApp());
class BrandApp extends StatelessWidget {
const BrandApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: lightTheme,
darkTheme: darkTheme,
themeMode: ThemeMode.system,
home: const Scaffold(body: Center(child: SuccessBanner())),
);
}
}
class SuccessBanner extends StatelessWidget {
const SuccessBanner({super.key});
@override
Widget build(BuildContext context) {
final brand = context.brand;
return Container(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
decoration: BoxDecoration(
color: brand.success,
borderRadius: BorderRadius.circular(12),
),
child: Text(
'Saved',
style: Theme.of(context)
.textTheme
.titleMedium
?.copyWith(color: brand.onSuccess),
),
);
}
}SuccessBanner has no knowledge of light or dark mode. The theme chosen by themeMode decides which BrandColors instance it receives.
How lerp is used
When themeMode changes, MaterialApp animates between the old and new ThemeData through AnimatedTheme. ThemeData.lerp interpolates the color scheme, text theme and component themes. It calls your extension's lerp for each registered extension type.
This gives you two rules:
- Register the same extension type in both themes. If one theme lacks it, there is nothing to interpolate against, and the value can jump instead of fading.
- Interpolate every field in
lerp. If you forget a field and return the old value, that field stays frozen during the transition and then snaps to the new value at the end.
Fields that cannot be interpolated smoothly, such as booleans, enums and strings, need a choice. A common pattern is t < 0.5 ? this.flag : other.flag. Doubles use lerpDouble from dart:ui, and EdgeInsets, TextStyle and BorderRadius have their own static lerp methods.
Tokens that are not colors
Extensions are not limited to colors. Any value that should vary by theme can live in one. This example holds spacing and radius tokens:
import 'dart:ui' show lerpDouble;
import 'package:flutter/material.dart';
@immutable
class Spacing extends ThemeExtension<Spacing> {
const Spacing({required this.small, required this.medium, required this.cardRadius});
final double small;
final double medium;
final double cardRadius;
@override
Spacing copyWith({double? small, double? medium, double? cardRadius}) {
return Spacing(
small: small ?? this.small,
medium: medium ?? this.medium,
cardRadius: cardRadius ?? this.cardRadius,
);
}
@override
Spacing lerp(ThemeExtension<Spacing>? other, double t) {
if (other is! Spacing) return this;
return Spacing(
small: lerpDouble(small, other.small, t)!,
medium: lerpDouble(medium, other.medium, t)!,
cardRadius: lerpDouble(cardRadius, other.cardRadius, t)!,
);
}
}Use this approach only for values that really change between themes, such as a compact theme and a comfortable one. If a value is the same everywhere, a plain const is simpler.
Building tokens from the ColorScheme
Hard-coded presets are fine when the app has a fixed brand. They are a poor fit when the ColorScheme can change, for example with dynamic color from the platform. A hard-coded green may then clash with the generated palette.
In that case, create the extension from the scheme you already have:
ThemeData buildTheme(ColorScheme scheme) {
final isDark = scheme.brightness == Brightness.dark;
return ThemeData(
colorScheme: scheme,
extensions: [
BrandColors(
success: isDark ? const Color(0xFF81C784) : const Color(0xFF2E7D32),
onSuccess: isDark ? const Color(0xFF003910) : Colors.white,
),
],
);
}One buildTheme function used for both light and dark schemes also removes a common error, where the two ThemeData objects drift apart over time.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `Null check operator used on a null value` | `extension<T>()` returned `null` because the extension is not registered in the active theme | Register it in both `theme` and `darkTheme`, or use a fallback getter |
| Colors jump at the end of a theme change | `lerp` returns `this` or skips a field | Interpolate every field |
| Dark mode shows light values | Both themes use the light preset | Check the `extensions` list in `darkTheme` |
| Extension is missing inside a dialog or route | The widget is below a different `Theme` that was built without extensions | Use `Theme.of(context).copyWith(...)` instead of building a new `ThemeData` |
| Custom value reverts after `copyWith` | `ThemeData.copyWith(extensions: ...)` replaces the whole extension list | Pass every extension you need, not only the changed one |
| Type mismatch error in `lerp` | Class declared as `ThemeExtension<Other>` | The generic argument must be the class itself |
Testing an extension
Extensions are easy to test because they are plain Dart objects. A useful check is that lerp at 0 and 1 returns the endpoints:
import 'package:flutter_test/flutter_test.dart';
void main() {
test('BrandColors lerp reaches both endpoints', () {
final start = BrandColors.light.lerp(BrandColors.dark, 0);
final end = BrandColors.light.lerp(BrandColors.dark, 1);
expect(start.success, BrandColors.light.success);
expect(end.success, BrandColors.dark.success);
});
}This test catches a forgotten field or a swapped argument before a user sees a flicker.
Exercise
A teammate adds BrandColors only to lightTheme. The app uses context.brand, which reads Theme.of(context).extension<BrandColors>()!. What happens when the user switches to dark mode, and what are two ways to fix it?
Show answer
The ! throws a null check error, because darkTheme has no BrandColors registered and extension<BrandColors>() returns null. Fix 1: register a dark BrandColors instance in darkTheme.extensions. Fix 2: change the getter to use a fallback, for example ?? BrandColors.light, although a dedicated dark palette is better because the light colors will have poor contrast on dark surfaces.
Exercise
Add a warning and onWarning color pair to BrandColors. Which three places must change so the app still works and animates correctly?
Show answer
The constructor and fields, copyWith, and lerp must include the new pair. The light and dark presets (or the buildTheme function) must also supply values for it. If lerp is not updated, the new colors will not fade during a theme change and will snap at the end instead.