Why You Should Be Using Flutter Theme Extensions
So I was thinking about writing an article about Flutter Theme Extensions. But there’s really not much to say about them. First you make a ThemeExtension
class:
@immutable
class Foo extends ThemeExtension<Foo> {
const Foo({
…
}); @override
Foo copyWith({
…,
}) {
return Foo(
…
);
} @override
Foo lerp(ThemeExtension<Foo>? other, double t) {
return Foo(…);
}
Then whenever you make a theme you insert your custom theme data using copyWith()
ThemeData.dark().copyWith(
extensions: <ThemeExtension<dynamic>>[
Foo(…),
],
),
And then finally you retrieve it using extension()
Theme.of(context).extension<Foo>()!;
Easy peasy. So I’m not going to focus on that. Instead I’m going to focus on another question: why you should be using theme extensions in the first place?
Why You Should Never Save You Widgets
So you may have noticed in Flutter build()
returns a Widget
. And a Widget
is an object. And objects can be saved to variables. So maybe instead of building a widget every single time you can cache the widget.