toMaterialColor property
MaterialColor
get
toMaterialColor
Generates a full 10-shade MaterialColor swatch (50-900) from a single base color.
This is essential for defining ThemeData.primarySwatch as Flutter requires
a MaterialColor for this property, not just a Color.
The base color is used to mathematically derive all lighter and darker shades.
@returns A new MaterialColor object.
Example:
final customColor = Color(0xFF1ABC9C);
final customSwatch = customColor.toMaterialColor;
ThemeData(primarySwatch: customSwatch)
Implementation
MaterialColor get toMaterialColor {
List<double> strengths = <double>[.05];
Map<int, Color> swatch = <int, Color>{};
final int red = (r * 255.0).round().clamp(0, 255),
green = (g * 255.0).round().clamp(0, 255),
blue = (b * 255.0).round().clamp(0, 255);
for (int i = 1; i < 10; i++) {
strengths.add(0.1 * i);
}
for (var strength in strengths) {
final double ds = 0.5 - strength;
swatch[(strength * 1000).round()] = Color.fromRGBO(
red + ((ds < 0 ? red : (255 - red)) * ds).round(),
green + ((ds < 0 ? green : (255 - green)) * ds).round(),
blue + ((ds < 0 ? blue : (255 - blue)) * ds).round(),
1,
);
}
return MaterialColor(value, swatch);
}