Reputation: 571
i would like to insert an hexadecimal color code in the primarySwatch property, here is what i have tried to do :
return MaterialApp(
title: 'Login Demo',
theme: ThemeData(
// brightness: Brightness.dark,
primarySwatch: Color(0xFF3399FF),
Upvotes: 9
Views: 10762
Reputation: 191
MaterialColor requires shades. So you need a function like:
MaterialColor getMaterialColor() {
int colorValue = 0xFFC9F5FC;
Color color = Color(colorValue);
Map<int, Color> shades = [50, 100, 200, 300, 400, 500, 600, 700, 800, 900]
.asMap()
.map((key, value) => MapEntry(value, color.withOpacity(1 - (1 - (key + 1) / 10))));
return MaterialColor(colorValue, shades);
}
or you can use it as extension like:
extension ToMaterialColor on Color {
MaterialColor get asMaterialColor {
Map<int, Color> shades = [50, 100, 200, 300, 400, 500, 600, 700, 800, 900]
.asMap()
.map((key, value) => MapEntry(value, withOpacity(1 - (1 - (key + 1) / 10))));
return MaterialColor(value, shades);
}
}
...
primarySwatch: Color(0xFFC9F5FC).asMaterialColor
Upvotes: 1
Reputation: 872
This tutorial shows a function that can build primarySwatches from a Color
.
MaterialColor buildMaterialColor(Color color) {
List strengths = <double>[.05];
Map<int, Color> swatch = {};
final int r = color.red, g = color.green, b = color.blue;
for (int i = 1; i < 10; i++) {
strengths.add(0.1 * i);
}
strengths.forEach((strength) {
final double ds = 0.5 - strength;
swatch[(strength * 1000).round()] = Color.fromRGBO(
r + ((ds < 0 ? r : (255 - r)) * ds).round(),
g + ((ds < 0 ? g : (255 - g)) * ds).round(),
b + ((ds < 0 ? b : (255 - b)) * ds).round(),
1,
);
});
return MaterialColor(color.value, swatch);
}
Then in the theme you can do:
primarySwatch: buildMaterialColor(Color(0xFF3399FF)),
Upvotes: 18
Reputation: 7492
You can set primarySwatch property like below.
Map<int, Color> color =
{
50:Color.fromRGBO(51, 153, 255, .1),
100:Color.fromRGBO(51, 153, 255, .2),
200:Color.fromRGBO(51, 153, 255, .3),
300:Color.fromRGBO(51, 153, 255, .4),
400:Color.fromRGBO(51, 153, 255, .5),
500:Color.fromRGBO(51, 153, 255, .6),
600:Color.fromRGBO(51, 153, 255, .7),
700:Color.fromRGBO(51, 153, 255, .8),
800:Color.fromRGBO(51, 153, 255, .9),
900:Color.fromRGBO(51, 153, 255, 1),
};
...
primarySwatch: MaterialColor(0xFF3399FF, color)
Upvotes: 1