Skip to content

Instantly share code, notes, and snippets.

@onhate
Created September 27, 2021 17:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save onhate/45d7a949722ef2c53019f12e1b9feb2e to your computer and use it in GitHub Desktop.
Save onhate/45d7a949722ef2c53019f12e1b9feb2e to your computer and use it in GitHub Desktop.
Hex string color to MaterialColor with swatches
import 'package:flutter/material.dart';
class HexColor extends Color {
static int getColorFromHex(String hexColor) {
hexColor = hexColor.toUpperCase().replaceAll("#", "");
if (hexColor.length == 6) {
hexColor = "FF" + hexColor;
}
return int.parse(hexColor, radix: 16);
}
HexColor(final String hexColor) : super(getColorFromHex(hexColor));
}
class HexColorMaterial extends MaterialColor {
static int getColor(String hexColor) {
Color color = HexColor(hexColor).withOpacity(1);
return color.value;
}
static Map<int, Color> getSwatch(String hexColor) {
Color color = Color(getColor(hexColor));
return {
50: color.withOpacity(.1),
100: color.withOpacity(.2),
200: color.withOpacity(.3),
300: color.withOpacity(.4),
400: color.withOpacity(.5),
500: color.withOpacity(.6),
600: color.withOpacity(.7),
700: color.withOpacity(.8),
800: color.withOpacity(.9),
900: color.withOpacity(1),
};
}
HexColorMaterial(final String hexColor)
: super(getColor(hexColor), getSwatch(hexColor));
}
final theme = ThemeData(
primarySwatch: HexColorMaterial('#000'),
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment