How do I use hexadecimal color strings in Flutter?
Solution 1
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 leading "#".
static Color fromHex(String hexString) {
final buffer = StringBuffer();
if (hexString.length == 6 || hexString.length == 7) buffer.write('ff');
buffer.write(hexString.replaceFirst('#', ''));
return Color(int.parse(buffer.toString(), radix: 16));
}
/// Prefixes a hash sign if [leadingHashSign] is set to `true` (default is `true`).
String toHex({bool leadingHashSign = true}) => '${leadingHashSign ? '#' : ''}'
'${alpha.toRadixString(16).padLeft(2, '0')}'
'${red.toRadixString(16).padLeft(2, '0')}'
'${green.toRadixString(16).padLeft(2, '0')}'
'${blue.toRadixString(16).padLeft(2, '0')}';
}
The fromHex
method could also be declared in a mixin
or class
because the HexColor
name needs to be explicitly specified in order to use it, but the extension is useful for the toHex
method, which can be used implicitly. Here is an example:
void main() {
final Color color = HexColor.fromHex('#aabbcc');
print(color.toHex());
print(const Color(0xffaabbcc).toHex());
}
Disadvantage of using hex strings
Many of the other answers here show how you can dynamically create a Color
from a hex string, like I did above. However, doing this means that the color cannot be a const
.
Ideally, you would assign your colors the way I explained in the first part of this answer, which is more efficient when instantiating colors a lot, which is usually the case for Flutter widgets.
Solution 2
The Color
class expects an ARGB integer. Since you try to use it with an RGB value, represent it as int and prefix it with 0xff
.
Color mainColor = Color(0xffb74093);
If you get annoyed by this and still wish to use strings, you can extend Color
and add a string constructor
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));
}
Usage
Color color1 = HexColor("b74093");
Color color2 = HexColor("#b74093");
Color color3 = HexColor("#88b74093"); // If you wish to use ARGB format
Solution 3
If you want to use the hexadecimal code of a color which is in the format #123456, then it is very easy to do. Create a variable of type Color and assign the following values to it.
Color myHexColor = Color(0xff123456)
// Here you notice I use the 0xff and that is the opacity or transparency
// of the color and you can also change these values.
Use myHexColor and you are ready to go.
If you want to change the opacity of color direct from the hexadecimal code, then change the ff value in 0xff to the respective value from the table below. (alternatively you can use
myHexColor.withOpacity(0.2)
it is easier way to do it. 0.2 is mean 20% opacity)
Hexadecimal opacity values
100% — FF
95% — F2
90% — E6
85% — D9
80% — CC
75% — BF
70% — B3
65% — A6
60% — 99
55% — 8C
50% — 80
45% — 73
40% — 66
35% — 59
30% — 4D
25% — 40
20% — 33
15% — 26
10% — 1A
5% — 0D
0% — 00
Solution 4
How to use a hexadecimal color code #B74093 in Flutter
Simply remove the #
sign from the hexadecimal color code and add 0xFF with the color code inside the Color class:
#b74093
will become Color(0xffb74093)
in Flutter
#B74093
will become Color(0xFFB74093)
in Flutter
Tthe ff or FF
in Color(0xFFB74093)
defines the opacity.
Hexadecimal colors example with all opacity types in Dartpad
Solution 5
Easy way:
String color = yourHexColor.replaceAll('#', '0xff');
Usage:
Container(
color: Color(int.parse(color)),
)
creativecreatorormaybenot
Updated on July 08, 2022Comments
-
creativecreatorormaybenot almost 2 years
How do I convert a hexadecimal color string like
#b74093
to aColor
in Flutter?I want to use a HEX color code in Dart.
-
creativecreatorormaybenot almost 6 yearsI needed the "leading FF" for Flutter's
ThemeData
. -
KevinM over 5 yearsI like this solution for its simplicity, but as @creativecreatorormaybenot mentioned, the leading FF is still required.
-
xhinoda about 5 yearsthis is really great! also works with LinearGradient.
-
Alvin Konda over 4 yearsThansk to @jeroen-meijer for the edit. In fact you can use this one liner as well if you feel fancy
Color(int.parse('#000000'.replaceAll('#', '0xff')))
-
leeCoder over 4 yearsthe HexColor class did not work for MaterialColor for me, it keeps complaining of the second parameter. Please help here
-
Łukasz Wiśniewski almost 4 yearsYou can't have static method extension in dart yet github.com/dart-lang/language/issues/723
-
Gauris Javier almost 4 yearsIt's a good idea to save this reference, although the .withOpacity(0.2) is useful enough i most of the cases.
-
HJo almost 4 yearsI'm just surprised that you can pass 0xFF as part of an int
-
creativecreatorormaybenot almost 4 years@HamishJohnson
0x
just indicates that the following digits will be parsed as a hexadecimal 🙃 -
madhu131313 over 3 yearsyour solution is working for me. Are there any downsides, anyone?
-
Nipun Ravisara over 3 yearsThis is grate but sometimes It shows whats going below the widgets for example when
SliverAppBar
scrolls it shows whats below that widget because of I'm reducing the opacity. Is there anyway to fade the color without reducing opacity. -
Zakria Khan over 3 years@nipunravisara get the hex of the color and use 100% opacity
-
Nipun Ravisara over 3 years@ZakriaKhan Thanks actually I found a way. stackoverflow.com/questions/65856982/…
-
Peter Mortensen about 3 yearsLots of magic numbers. Aren't named constants supported in this language / environment?
-
Peter Mortensen about 3 yearsLots of magic numbers. Aren't named constants supported in this language / environment?
-
Peter Mortensen almost 3 yearsAnd
(1 << (4 * (len - 1 - i)))
is repeated three times. -
Pratik Butani almost 3 years
.toUpperCase()
giving error. Removed it and working now -
Ankit over 2 yearsIs there any way to use 50% or any % of these colors? Like something Color(0xFF183451)[50]?
-
creativecreatorormaybenot over 2 years@Ankit You can use this table and replace the
FF
in the leading0xFF
of yourColor
object with the value you need. So in your case that would beColor(0x80183451)
. -
Balaji over 2 yearsHow do I convert
#0ff
this string?, It has only three digits -
creativecreatorormaybenot over 2 years@BalajiRamadoss I think the standard convention would make this
0xff00ffff
and you could write a function for it. -
Balaji over 2 yearsYes thanks, I figured it out, I have to double the characters "0ff" to "00ffff"
-
TechAurelian over 2 yearsOr
Color(int.parse(hexString.replaceFirst('#', '0xff')))
if I know for sure that the input hex string is in#RRGGBB
format (such as#45a3df
). -
MNBWorld about 2 yearsNow a days the best way to do this is to use the flutter hex color plugin from pub.dev and the import the package.
-
creativecreatorormaybenot about 2 years@MNBWorld I highly disagree with that sentiment. The package only implements a version of the extension class from my answer with less features. This leads to poorer customization of how you want to handle HEX codes (which might be specific to your app). And in general, it is preferrable to use the
const
constructors withColor
. -
Tremmillicious about 2 yearsWhat this is a bad answer and bad coding honestly, so many magic numbers, too much code for a one liner