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 BrandStyle extends ThemeExtension<BrandStyle> {
4 final Color color;
5 final BorderRadius borderRadius;
6
7 const BrandStyle({required this.color, required this.borderRadius});
8
9 @override
10 BrandStyle copyWith({Color? color, BorderRadius? borderRadius}) => BrandStyle(
11 color: color ?? this.color,
12 borderRadius: borderRadius ?? this.borderRadius,
13 );
14
15 @override
16 BrandStyle lerp(BrandStyle? other, double t) {
17 if (other is! BrandStyle) {
18 return this;
19 }
20
21 return BrandStyle(
22 color: .lerp(color, other.color, t)!,
23 borderRadius: .lerp(borderRadius, other.borderRadius, t)!,
24 );
25 }
26}
27

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

1FThemeData(
2 colors: FThemes.neutral.light.touch.colors,
3 // ... other theme properties
4 touch: true,
5 extensions: [
6 const BrandStyle(
7 color: Color(0xFF6366F1),
8 borderRadius: .all(.circular(8)),
9 ),
10 ],
11);
12

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

1final theme = FThemes.neutral.light.touch.copyWith(
2 extensions: [
3 const BrandStyle(
4 color: Color(0xFF6366F1),
5 borderRadius: .all(.circular(8)),
6 ),
7 ],
8);
9

Accessing the Properties

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

1@override
2Widget build(BuildContext context) {
3 final brand = context.theme.extension<BrandStyle>();
4 return DecoratedBox(
5 decoration: BoxDecoration(
6 color: brand.color,
7 borderRadius: brand.borderRadius,
8 ),
9 );
10}
11

Optionally, we recommend creating a getter on FThemeData:

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

On this page