Guides

Adding Theme Properties

Extend Forui themes with application-specific properties using Flutter's ThemeExtension system.

Forui themes can be extended with your own application-specific properties using Flutter's ThemeExtension system.

Create a Theme Extension

Theme extensions must extend ThemeExtension and implement copyWith() and lerp().

1import 'package:flutter/material.dart';
2
3class BrandColor extends ThemeExtension<BrandColor> {
4 final Color color;
5
6 const BrandColor({required this.color});
7
8 @override
9 BrandColor copyWith({Color? color}) => BrandColor(color: color ?? this.color);
10
11 @override
12 BrandColor lerp(BrandColor? other, double t) {
13 if (other is! BrandColor) {
14 return this;
15 }
16
17 return BrandColor(color: Color.lerp(color, other.color, t)!);
18 }
19}
20

Add the extension to FThemeData(...) via its extensions parameter:

1FThemeData(
2 colors: FColors.neutral.light,
3 // ... other theme properties
4 touch: true,
5 extensions: [const BrandColor(color: Color(0xFF6366F1))],
6);
7

You can also add extensions to existing themes using copyWith(...):

1final theme = FThemeData(
2 touch: true,
3 colors: FColors.neutral.light,
4).copyWith(extensions: [const BrandColor(color: Color(0xFF6366F1))]);
5

Accessing the Properties

Retrieve your custom theme extension via extension<T>():

1@override
2Widget build(BuildContext context) {
3 final brand = context.theme.extension<BrandColor>();
4 return ColoredBox(color: brand.color);
5}
6

Optionally, we recommend creating a getter on FThemeData:

1extension BrandColorExtension on FThemeData {
2 BrandColor get brand => extension<BrandColor>();
3}
4

On this page