Last active
October 19, 2022 06:14
-
-
Save nicky-song/244be04f1dbdba52788017f008477484 to your computer and use it in GitHub Desktop.
Flutter: Create MaterialColor from a hex color
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
MaterialColor createMaterialColor(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); | |
} | |
for (var strength in strengths) { | |
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); | |
} |
Thanks much for this man! Works great!
My Dart linter gave a warning: "[dart avoid_function_literals_in_foreach_calls] [I] Avoid use forEach
with a function literal"
Solution for me was to use for
instead: https://stackoverflow.com/a/68087751
It works pretty well in my project integration at my uni. I try many alternatives to customize the primary swatch color and fails each time. So, thank you a lot! :)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The argument type 'Map<dynamic, dynamic>' can't be assigned to the parameter type 'Map<int, Color>'.