How to convert a hexadecimal color string like #b74093
to a Color
in Flutter
In Flutter the Color
class only accepts integers as parameters, or there is the possibility to use the named constructors fromARGB
and fromRGBO
.
So we only need to convert the string #b74093
to an integer value. Also we need to respect that opacity always needs to be specified.255
(full) opacity is represented by the hexadecimal value FF
. This already leaves us with 0xFF
. Now, we just need to append our color string like this:
const color = const Color(0xffb74093); // Second `const` is optional in assignments.
The letters can by choice be capitalized or not:
const color = const Color(0xFFB74093);
If you want to use percentage opacity values, you can replace the first FF
with the values from this table (also works for the other color channels).
Extension class
Starting with Dart 2.6.0
, you can create an extension
for the Color
class that lets you use hexadecimal color strings to create a Color
object:
extension HexColor on Color {
/// String is in the format "aabbcc" or "ffaabbcc" with an optional…