ThemeExtension in Flutter: solved exercise with custom color system

ThemeExtension in Flutter: solved exercise with custom color system

ThemeData covers Material Design colors but is often not enough for a custom design system. ThemeExtension lets you add your own color, typography, and spacing tokens to Flutter’s theme, accessible via Theme.of(context).extension<MyExtension>().

Problem statement

Build a design token system that:

  • Defines an AppColors extension with semantic colors (success, warning, danger, info).
  • Defines an AppSpacing extension with spacing values (xs, sm, md, lg, xl).
  • Integrates both extensions into ThemeData for light and dark mode.
  • Implements lerp for smooth transitions when switching themes.
  • Uses tokens in real widgets with no direct color references.

Dependencies

None additional — ThemeExtension is part of the Flutter SDK.

Full solution

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
import 'package:flutter/material.dart';

// ── Semantic color tokens ──────────────────────────────────────────────────────
@immutable
class AppColors extends ThemeExtension<AppColors> {
  final Color success;
  final Color successContainer;
  final Color warning;
  final Color warningContainer;
  final Color danger;
  final Color dangerContainer;
  final Color info;
  final Color infoContainer;
  final Color cardBackground;
  final Color divider;

  const AppColors({
    required this.success,
    required this.successContainer,
    required this.warning,
    required this.warningContainer,
    required this.danger,
    required this.dangerContainer,
    required this.info,
    required this.infoContainer,
    required this.cardBackground,
    required this.divider,
  });

  // Light theme
  static const light = AppColors(
    success: Color(0xFF2E7D32),
    successContainer: Color(0xFFE8F5E9),
    warning: Color(0xFFF57F17),
    warningContainer: Color(0xFFFFF8E1),
    danger: Color(0xFFC62828),
    dangerContainer: Color(0xFFFFEBEE),
    info: Color(0xFF0277BD),
    infoContainer: Color(0xFFE1F5FE),
    cardBackground: Color(0xFFFFFFFF),
    divider: Color(0xFFE0E0E0),
  );

  // Dark theme
  static const dark = AppColors(
    success: Color(0xFF81C784),
    successContainer: Color(0xFF1B5E20),
    warning: Color(0xFFFFD54F),
    warningContainer: Color(0xFF4E342E),
    danger: Color(0xFFEF9A9A),
    dangerContainer: Color(0xFF4A1010),
    info: Color(0xFF4FC3F7),
    infoContainer: Color(0xFF01579B),
    cardBackground: Color(0xFF1E1E1E),
    divider: Color(0xFF2C2C2C),
  );

  @override
  AppColors copyWith({
    Color? success, Color? successContainer,
    Color? warning, Color? warningContainer,
    Color? danger, Color? dangerContainer,
    Color? info, Color? infoContainer,
    Color? cardBackground, Color? divider,
  }) => AppColors(
    success: success ?? this.success,
    successContainer: successContainer ?? this.successContainer,
    warning: warning ?? this.warning,
    warningContainer: warningContainer ?? this.warningContainer,
    danger: danger ?? this.danger,
    dangerContainer: dangerContainer ?? this.dangerContainer,
    info: info ?? this.info,
    infoContainer: infoContainer ?? this.infoContainer,
    cardBackground: cardBackground ?? this.cardBackground,
    divider: divider ?? this.divider,
  );

  // lerp enables smooth animations when changing themes
  @override
  AppColors lerp(AppColors? other, double t) {
    if (other == null) return this;
    return AppColors(
      success: Color.lerp(success, other.success, t)!,
      successContainer: Color.lerp(successContainer, other.successContainer, t)!,
      warning: Color.lerp(warning, other.warning, t)!,
      warningContainer: Color.lerp(warningContainer, other.warningContainer, t)!,
      danger: Color.lerp(danger, other.danger, t)!,
      dangerContainer: Color.lerp(dangerContainer, other.dangerContainer, t)!,
      info: Color.lerp(info, other.info, t)!,
      infoContainer: Color.lerp(infoContainer, other.infoContainer, t)!,
      cardBackground: Color.lerp(cardBackground, other.cardBackground, t)!,
      divider: Color.lerp(divider, other.divider, t)!,
    );
  }
}

// ── Spacing tokens ─────────────────────────────────────────────────────────────
@immutable
class AppSpacing extends ThemeExtension<AppSpacing> {
  final double xs;
  final double sm;
  final double md;
  final double lg;
  final double xl;
  final double xxl;

  const AppSpacing({
    this.xs = 4, this.sm = 8, this.md = 16,
    this.lg = 24, this.xl = 32, this.xxl = 48,
  });

  static const standard = AppSpacing();

  @override
  AppSpacing copyWith({
    double? xs, double? sm, double? md,
    double? lg, double? xl, double? xxl,
  }) => AppSpacing(
    xs: xs ?? this.xs, sm: sm ?? this.sm, md: md ?? this.md,
    lg: lg ?? this.lg, xl: xl ?? this.xl, xxl: xxl ?? this.xxl,
  );

  @override
  AppSpacing lerp(AppSpacing? other, double t) {
    if (other == null) return this;
    double _l(double a, double b) => a + (b - a) * t;
    return AppSpacing(
      xs: _l(xs, other.xs), sm: _l(sm, other.sm), md: _l(md, other.md),
      lg: _l(lg, other.lg), xl: _l(xl, other.xl), xxl: _l(xxl, other.xxl),
    );
  }
}

// ── Quick context access ───────────────────────────────────────────────────────
extension AppTheme on BuildContext {
  AppColors get appColors =>
      Theme.of(this).extension<AppColors>() ?? AppColors.light;
  AppSpacing get appSpacing =>
      Theme.of(this).extension<AppSpacing>() ?? AppSpacing.standard;
}

// ── Theme configuration ────────────────────────────────────────────────────────
ThemeData _buildTheme(Brightness brightness) {
  final isDark = brightness == Brightness.dark;
  return ThemeData(
    useMaterial3: true,
    brightness: brightness,
    colorScheme: ColorScheme.fromSeed(
      seedColor: const Color(0xFF1565C0),
      brightness: brightness,
    ),
    extensions: [
      isDark ? AppColors.dark : AppColors.light,
      AppSpacing.standard,
    ],
  );
}

// ── Main ───────────────────────────────────────────────────────────────────────
void main() => runApp(const ThemeExtensionDemo());

class ThemeExtensionDemo extends StatefulWidget {
  const ThemeExtensionDemo({super.key});
  @override
  State<ThemeExtensionDemo> createState() => _ThemeExtensionDemoState();
}

class _ThemeExtensionDemoState extends State<ThemeExtensionDemo> {
  ThemeMode _themeMode = ThemeMode.light;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: _buildTheme(Brightness.light),
      darkTheme: _buildTheme(Brightness.dark),
      themeMode: _themeMode,
      home: HomePage(
        onToggleTheme: () => setState(() {
          _themeMode = _themeMode == ThemeMode.light
              ? ThemeMode.dark
              : ThemeMode.light;
        }),
      ),
    );
  }
}

// ── Home screen ────────────────────────────────────────────────────────────────
class HomePage extends StatelessWidget {
  final VoidCallback onToggleTheme;
  const HomePage({super.key, required this.onToggleTheme});

  @override
  Widget build(BuildContext context) {
    final colors = context.appColors;
    final spacing = context.appSpacing;

    return Scaffold(
      appBar: AppBar(
        title: const Text('ThemeExtension'),
        actions: [
          IconButton(
            icon: const Icon(Icons.brightness_6),
            onPressed: onToggleTheme,
            tooltip: 'Toggle theme',
          ),
        ],
      ),
      body: ListView(
        padding: EdgeInsets.all(spacing.md),
        children: [
          const _SectionTitle('Semantic color tokens'),
          SizedBox(height: spacing.sm),
          _StatusCard(
            label: 'Success',
            icon: Icons.check_circle,
            foreground: colors.success,
            background: colors.successContainer,
            message: 'The operation completed successfully.',
          ),
          SizedBox(height: spacing.sm),
          _StatusCard(
            label: 'Warning',
            icon: Icons.warning_amber,
            foreground: colors.warning,
            background: colors.warningContainer,
            message: 'Please review your data before continuing.',
          ),
          SizedBox(height: spacing.sm),
          _StatusCard(
            label: 'Error',
            icon: Icons.error,
            foreground: colors.danger,
            background: colors.dangerContainer,
            message: 'Could not connect to the server.',
          ),
          SizedBox(height: spacing.sm),
          _StatusCard(
            label: 'Info',
            icon: Icons.info,
            foreground: colors.info,
            background: colors.infoContainer,
            message: 'Flutter 3.32 is now available.',
          ),

          SizedBox(height: spacing.lg),
          const _SectionTitle('Spacing tokens'),
          SizedBox(height: spacing.sm),
          ...[
            ('xs', spacing.xs), ('sm', spacing.sm), ('md', spacing.md),
            ('lg', spacing.lg), ('xl', spacing.xl), ('xxl', spacing.xxl),
          ].map((t) => Padding(
                padding: EdgeInsets.only(bottom: spacing.xs),
                child: Row(
                  children: [
                    SizedBox(
                      width: 40,
                      child: Text(t.$1,
                          style: const TextStyle(fontWeight: FontWeight.bold)),
                    ),
                    Container(
                      width: t.$2 * 3,
                      height: 20,
                      decoration: BoxDecoration(
                        color: colors.info,
                        borderRadius: BorderRadius.circular(4),
                      ),
                    ),
                    SizedBox(width: spacing.sm),
                    Text('${t.$2.round()}px'),
                  ],
                ),
              )),

          SizedBox(height: spacing.lg),
          const _SectionTitle('Card using tokens'),
          SizedBox(height: spacing.sm),
          Container(
            padding: EdgeInsets.all(spacing.md),
            decoration: BoxDecoration(
              color: colors.cardBackground,
              border: Border.all(color: colors.divider),
              borderRadius: BorderRadius.circular(12),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(0.05),
                  blurRadius: 8,
                  offset: const Offset(0, 2),
                ),
              ],
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text('Custom component',
                    style: Theme.of(context).textTheme.titleMedium),
                SizedBox(height: spacing.xs),
                Divider(color: colors.divider),
                SizedBox(height: spacing.xs),
                const Text('This card uses design system tokens. '
                    'Toggle dark mode with the button above to see '
                    'the animated theme transition.'),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

class _SectionTitle extends StatelessWidget {
  final String text;
  const _SectionTitle(this.text);
  @override
  Widget build(BuildContext context) => Text(
        text,
        style: Theme.of(context)
            .textTheme
            .titleSmall
            ?.copyWith(color: Theme.of(context).colorScheme.primary),
      );
}

class _StatusCard extends StatelessWidget {
  final String label;
  final IconData icon;
  final Color foreground;
  final Color background;
  final String message;
  const _StatusCard({
    required this.label, required this.icon,
    required this.foreground, required this.background, required this.message,
  });

  @override
  Widget build(BuildContext context) {
    final spacing = context.appSpacing;
    return Container(
      padding: EdgeInsets.all(spacing.sm),
      decoration: BoxDecoration(
        color: background, borderRadius: BorderRadius.circular(8),
      ),
      child: Row(
        children: [
          Icon(icon, color: foreground),
          SizedBox(width: spacing.sm),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(label,
                    style: TextStyle(fontWeight: FontWeight.bold, color: foreground)),
                Text(message, style: TextStyle(color: foreground)),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

When to use ThemeExtension vs ColorScheme

ColorSchemeThemeExtension
ForStandard Material Design colorsCustom product design tokens
AccessTheme.of(ctx).colorScheme.primaryTheme.of(ctx).extension<AppColors>()
Auto lerpYesYes (if you implement lerp)
Use casesStandard Material appsCorporate design systems

Common mistakes

  • extension<T>() returns null: you forgot to add the extension to ThemeData.extensions. Make sure the extensions list includes it in both light and dark themes.
  • Not implementing lerp: without lerp, theme switching is abrupt instead of animated. Always implement lerp by calling Color.lerp on each field.
  • Using hardcoded colors in widgets: defeats the purpose of the token system. Always access colors through the extension so dark mode works automatically.

Practical use

ThemeExtension is the standard for apps with custom design systems: banking apps (transaction status colors), health apps (risk traffic lights), enterprise dashboards (metric colors).

Guided practice and next step

FAQ

Can I have multiple extensions in the same theme?

Yes. The extensions list in ThemeData accepts any number of ThemeExtension. Create as many as you need (colors, typography, border radii, spacing…).

Is ThemeExtension compatible with the Material theme generator?

Yes. Combine ColorScheme.fromSeed (for Material colors) with your own extensions. Both systems coexist without conflict.

How do I avoid calling Theme.of(context).extension<T>() in every widget?

Create a BuildContext extension as shown in the example (context.appColors). This is the cleanest pattern and avoids repeating the access boilerplate.