Sub topic 12
Adding Your Own Tokens with ThemeExtension
This chapter assumes basic Dart null safety, Flutter widget trees, MaterialApp, Scaffold, and BuildContext. You should also understand that ThemeData provides values inherited by widgets below a Theme in the widget tree.
Why use a ThemeExtension?
ColorScheme contains Material color roles such as primary, surface, and error. An application often needs additional design tokens. A design token is a named value that represents a visual decision, such as a success color, chart color, or custom spacing value.
You could store these values in constants, but constants do not change with the active theme. A ThemeExtension is a typed object that lets custom values live inside ThemeData. Widgets can then read the values through the same theme mechanism they use for Material values.
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
@immutable
class BrandColors extends ThemeExtension<BrandColors> {
const BrandColors({
required this.success,
required this.onSuccess,
});
final Color success;
final Color onSuccess;
@override
BrandColors copyWith({
Color? success,
Color? onSuccess,
}) {
return BrandColors(
success: success ?? this.success,
onSuccess: onSuccess ?? this.onSuccess,
);
}
@override
BrandColors lerp(
covariant BrandColors? other,
double t,
) {
if (other == null) return this;
return BrandColors(
success: Color.lerp(success, other.success, t)!,
onSuccess: Color.lerp(onSuccess, other.onSuccess, t)!,
);
}
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
const seed = Color(0xFF6750A4);
final lightTheme = ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: seed),
extensions: const [
BrandColors(
success: Color(0xFF2E7D32),
onSuccess: Colors.white,
),
],
);
final darkTheme = ThemeData(
colorScheme: ColorScheme.fromSeed(
seedColor: seed,
brightness: Brightness.dark,
),
extensions: const [
BrandColors(
success: Color(0xFF81C784),
onSuccess: Color(0xFF102010),
),
],
);
return MaterialApp(
theme: lightTheme,
darkTheme: darkTheme,
themeMode: ThemeMode.system,
home: const SuccessPage(),
);
}
}
class SuccessPage extends StatelessWidget {
const SuccessPage({super.key});
@override
Widget build(BuildContext context) {
final brand = Theme.of(context).extension<BrandColors>()!;
return Scaffold(
appBar: AppBar(title: const Text('Theme extension')),
body: Center(
child: Container(
padding: const EdgeInsets.all(16),
color: brand.success,
child: Text(
'Saved successfully',
style: TextStyle(color: brand.onSuccess),
),
),
),
);
}
}copyWith creates a modified copy while preserving values that were not supplied. Flutter uses lerp, which means “linear interpolation,” when it animates from one theme to another. For colors, Color.lerp produces an intermediate color.
How the value reaches a widget
The extensions list stores instances in ThemeData. Theme.of(context) finds the nearest theme and extension<BrandColors>() retrieves the instance by its Dart type.
The non-null assertion operator in the example is safe only when every active theme registers BrandColors. If an extension might be missing, use a nullable result and provide a fallback:
final brand = Theme.of(context).extension<BrandColors>();
final success = brand?.success ?? Colors.green;Common errors
- Registering the extension in
themebut not indarkTheme, causing a null result after switching modes. - Using the wrong generic type, such as requesting
ThemeExtension<OtherColors>. - Omitting
lerp, which prevents correct interpolation during theme changes. - Choosing foreground and background colors without checking their contrast.
- Reading a theme before the widget has a suitable
BuildContext.
A theme extension should contain values that describe the visual system. Keep application state, network data, and user preferences elsewhere.
Exercise
Why must a custom theme extension usually implement both copyWith and lerp?
Show answer
copyWith supports controlled changes to token values, while lerp lets Flutter interpolate the values when themes transition or animate.