2022: Use ThemeExtensions introduced in flutter 3
Here's a link! to the medium article I wrote.
- Create your ThemeExtension class
import 'package:flutter/material.dart';
@immutable
class MyCardTheme extends ThemeExtension<MyCardTheme> {
const MyCardTheme({
this.background = Colors.white,
this.shape = const RoundedRectangleBorder(
borderRadius: BorderRadius.all(
Radius.circular(8),
),
),
});
final Color background;
final ShapeBorder shape;
@override
MyCardTheme copyWith({
Color? background,
ShapeBorder? shape,
}) {
return MyCardTheme(
background: background ?? this.background,
shape: shape ?? this.shape,
);
}
@override
MyCardTheme lerp(ThemeExtension<MyCardTheme>? other, double t) {
if (other is! MyCardTheme) {
return this;
}
return MyCardTheme(
background: Color.lerp(background, other.background, t) ?? Colors.white,
shape: ShapeBorder.lerp(shape, other.shape, t) ??
const RoundedRectangleBorder(
borderRadius: BorderRadius.all(
Radius.circular(8),
),
),
);
}
@override
String toString() => 'MyCardTheme('
'background: $background, radius: $shape'
')';
}
- Create dark and light themes as per requirements
MyCardTheme lightCardTheme = MyCardTheme(
background: Colors.blueGrey[200]!,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.all(
Radius.circular(24),
),
),
);
MyCardTheme darkCardTheme = MyCardTheme(
background: Colors.blueGrey[800]!,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.all(
Radius.circular(24),
),
),
);
- Add extensions to your ThemeData for both, light and dark themes.
theme: ThemeData(
primarySwatch: Colors.green,
cardTheme: const CardTheme(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(
Radius.circular(8),
),
),
color: Colors.green,
),
extensions: <ThemeExtension<dynamic>>[
lightCardTheme,
],
),
darkTheme: ThemeData(
brightness: Brightness.dark,
primarySwatch: Colors.green,
cardTheme: const CardTheme(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(
Radius.circular(8),
),
),
color: Colors.green,
),
extensions: <ThemeExtension<dynamic>>[
darkCardTheme,
],
),
- Use them in your build methods
final MyCardTheme customCardTheme =
Theme.of(context).extension<MyCardTheme>()!;
Card(
shape: customCardTheme.shape,
color: customCardTheme.background,
child: Container(
padding: const EdgeInsets.all(16),
child: const Text('Card styled from custom theme')),
),
),