A simple Dart package exposing a Color class which can be used to create, convert, and compare colors.
- Add this to your package's
pubspec.yamlfile:
dependencies:
color: any- Get the package using your IDE's GUI or via command line with
$ pub get- Import the
color.dartfile in your app
import'package:color/color.dart';Color objects can be constructed using any of a few available constructors.
To create a color from rgb values, call
Color rgbColor =newColor.rgb(192, 255, 238);
RgbColor rgbColor =newRgbColor(192, 255, 238);Alternatively, a color can be created directly in a number of other color spaces.
RgbColor rgb =newRgbColor(192, 255, 238);
HexColor hex =newHexColor('c0ffee');
HslColor hsl =newHslColor(163.8, 100, 87.6);
XyzColor xyz =newXyzColor(72.931, 88.9, 94.204);
CielabColor cielab =newCielabColor(95.538, -23.02, 1.732);Colors are immutable, and can be created using const constructors.
RgbColor rgb =constRgbColor(192, 255, 238);Colors can be created directly from CSS3 color names.
RgbColor black =newRgbColor.name('black'); //factory constructor that returns a const RgbColorRgbColor white =RgbColor.namedColors['black']; //directly reference the const RgbColor without the factoryColors implementing the CssColorSpace interface can output a css string representation.
RgbColor rgb =newRgbColor(192, 255, 238);
HexColor hex =newHexColor('c0ffee');
HslColor hsl =newHslColor(163.8, 100, 87.6);
assert(rgb isCssColorSpace, true);
assert(hex isCssColorSpace, true);
assert(hsl isCssColorSpace, true);
print(rgb.toCssString()); //rgb(192, 255, 238)print(hex.toCssString()); //#c0ffeeprint(hsl.toCssString()); //hsl(163.8, 100.0%, 87.6%)Colors can be compared using the == operator, which will evaluate to true if the two colors share identical rgb values after being rounded to integers.
assert(newColor.hex('c0ffee') ==newColor.hex('c0ffee'));
assert(newColor.rgb('192, 255, 238') ==newColor.hex('c0ffee'));Colors can be converted from one color space to another by calling the appropriate toXXXColor method on them.
HslColor hsl =newRgbColor(192, 255, 238).toHslColor();Colors can be altered using a ColorFilter, which will return a new color in the same color space as the input color with that filter applied to it.
RgbColor grey =ColorFilter.greyscale(newRgbColor(192, 255, 238));
HslColor sepia =ColorFilter.sepia(newHslColor(163.8, 100, 87.6));