Want more control over your app's look and feel in Flutter? The default Material Design colors are a great start, but sometimes you need your own specific brand colors.
Luckily, Flutter lets you easily add your custom colors to your theme using ThemeExtension
. This makes your colors available throughout your app, just like the standard theme colors.
Here’s a simple way to do it:
Define Your Colors
Create a class that extends ThemeExtension
and list all your custom colors in it.
import 'package:flutter/material.dart';
class MyAppColors extends ThemeExtension<MyAppColors> {
final Color primaryBrand;
final Color secondaryBrand;
// Add all your custom colors here
const MyAppColors({
required this.primaryBrand,
required this.secondaryBrand,
});
// You'll need copyWith and lerp methods for ThemeExtension
// (Simplified example below, you'll need the full implementation)
MyAppColors copyWith({Color? primaryBrand, Color? secondaryBrand}) {
return MyAppColors(
primaryBrand: primaryBrand ?? this.primaryBrand,
secondaryBrand: secondaryBrand ?? this.secondaryBrand,
);
}
MyAppColors lerp(ThemeExtension<MyAppColors>? other, double t) {
if (other is! MyAppColors) {
return this;
}
return MyAppColors(
primaryBrand: Color.lerp(primaryBrand, other.primaryBrand, t)!,
secondaryBrand: Color.lerp(secondaryBrand, other.secondaryBrand, t)!,
);
}
// You can add factory methods for light/dark themes here
factory MyAppColors.light() => const MyAppColors(
primaryBrand: Color(0xFF123456),
secondaryBrand: Color(0xFFABCDEF),
);
// Add MyAppColors.dark() if you support dark mode
}
Add to Your Theme: Include your custom colors class instance in the extensions
list of your MaterialApp
's theme
property.
MaterialApp(
theme: ThemeData(
// ... other theme properties
extensions: <ThemeExtension<dynamic>>[
MyAppColors.light(), // Or .dark() based on theme mode
],
),
// ... rest of your app
)
3. Access Your Colors
Get your custom colors from anywhere in your app using BuildContext
.
You can create a simple extension on BuildContext
for easier access:
extension ThemeColors on BuildContext {
MyAppColors get colors => Theme.of(this).extension<MyAppColors>()!;
}
Then, access your colors like this:
Container(
color: context.colors.primaryBrand,
// ...
)
Using ThemeExtension
helps you manage your custom colors cleanly and makes them easy to access and update across your whole app.
Related Articles
You can also read more on how to create a custom theme and getting rid of the default Material theme in this article.