608

How do I convert a hexadecimal color string like #b74093 to a Color in Flutter?

I want to use a HEX color code in Dart.

creativecreatorormaybenot
  • 114,516
  • 58
  • 291
  • 402
  • 2
    in google chrome devtools you can quickly get the decimal numbers for a hex-style color; just click on the tiny color rectangle in the styles sidebar; in the popup you can switch the representation between HSLA, RGBA, HEX by clicking the chevron. Then you can use `Color.fromRGBO()` – ccpizza Dec 04 '20 at 17:25
  • Nice, but this is a programmer website so we generally want to know how to do it in code. – Stijn de Witt Sep 06 '22 at 12:20

34 Answers34

921

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.

Md. Yeasin Sheikh
  • 54,221
  • 7
  • 29
  • 56
creativecreatorormaybenot
  • 114,516
  • 58
  • 291
  • 402
  • You can't have static method extension in dart yet https://github.com/dart-lang/language/issues/723 – Łukasz Wiśniewski May 18 '20 at 15:03
  • I'm just surprised that you can pass 0xFF as part of an int – HJo Jun 18 '20 at 14:09
  • @HamishJohnson `0x` just indicates that the following digits will be parsed as a hexadecimal – creativecreatorormaybenot Jun 18 '20 at 16:11
  • Is there any way to use 50% or any % of these colors? Like something Color(0xFF183451)[50]? – Ankit Aug 12 '21 at 12:48
  • @Ankit You can use [this table](https://gist.github.com/creativecreatorormaybenot/8710f6f752f6a0f2cae13abb538f0e8e#hex-opacity-values) and replace the `FF` in the leading `0xFF` of your `Color` object with the value you need. So in your case that would be `Color(0x80183451)`. – creativecreatorormaybenot Aug 12 '21 at 12:59
  • How do I convert `#0ff` this string?, It has only three digits – Balaji Sep 07 '21 at 06:21
  • @BalajiRamadoss I think the standard convention would make this `0xff00ffff` and you could write a function for it. – creativecreatorormaybenot Sep 07 '21 at 17:08
  • Yes thanks, I figured it out, I have to double the characters "0ff" to "00ffff" – Balaji Sep 08 '21 at 06:27
  • Now a days the best way to do this is to use the flutter hex color plugin from ***pub.dev*** and the import the package. – MNBWorld Feb 04 '22 at 05:35
  • @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 with `Color`. – creativecreatorormaybenot Feb 04 '22 at 17:18
  • @creativecreatorormaybenot Regarding the cache/const problem... would it work if you set a static property `Map` within the extension to store the hex strings? (check if the hex string key exists in that static property before calculating?) – alex smith Oct 04 '22 at 08:04
  • @alexsmith Then you would still have to look up the hash map to obtain the color. I doubt that you will gain much from that and it will certainly not be `const` and can therefore not be used in `const` values. – creativecreatorormaybenot Oct 04 '22 at 18:13
  • @creativecreatorormaybenot Yes it won't be `const` indeed but it seems you're implying that looking up the hash map is also somewhat an expensive task. Is it? – alex smith Oct 07 '22 at 07:19
  • @alexsmith I am not implying that either of the operations is expensive. However, you will not be able to take advantage of `const` values. – creativecreatorormaybenot Oct 09 '22 at 10:23
275

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
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jossef Harush Kadouri
  • 32,361
  • 10
  • 130
  • 129
99

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
Zakria Khan
  • 1,897
  • 1
  • 17
  • 22
  • 2
    It's a good idea to save this reference, although the .withOpacity(0.2) is useful enough i most of the cases. – Gauris Javier Jun 08 '20 at 11:19
  • This 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. – Nipun Ravisara Jan 23 '21 at 07:58
  • @nipunravisara get the hex of the color and use 100% opacity – Zakria Khan Jan 24 '21 at 07:37
  • @ZakriaKhan Thanks actually I found a way. https://stackoverflow.com/questions/65856982/generate-custom-color-shades-from-parent-color-in-flutter/65857376#65857376 – Nipun Ravisara Jan 24 '21 at 11:22
70

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

The ff or FF in Color(0xFFB74093) defines the opacity.

Hexadecimal colors example with all opacity types in Dartpad

Enter image description here

Javeed Ishaq
  • 6,024
  • 6
  • 41
  • 60
50

Easy way:

String color = yourHexColor.replaceAll('#', '0xff');

Usage:

Container(
    color: Color(int.parse(color)),
)
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Serdar Polat
  • 3,992
  • 2
  • 12
  • 12
28

Thanks for asking this question, simples solution is as:

// Color to Hex String

colorToHexString(Color color) {
  return '#FF${color.value.toRadixString(16).substring(2, 8)}';
}

// Hex String to Color

hexStringToColor(String hexColor) {
  hexColor = hexColor.toUpperCase().replaceAll("#", "");
  if (hexColor.length == 6) {
    hexColor = "FF" + hexColor;
  }
  return Color(int.parse(hexColor, radix: 16));
}

// How to call function

String hexCode = colorToHexString(Colors.green);
Color bgColor = hexStringToColor(hexCode);
print("$hexCode = $bgColor");

Enjoy code and help others :)

Kamlesh
  • 5,233
  • 39
  • 50
27

A simple function without using a class:

Color _colorFromHex(String hexColor) {
  final hexCode = hexColor.replaceAll('#', '');
  return Color(int.parse('FF$hexCode', radix: 16));
}

You can use it like this:

Color color1 = _colorFromHex("b74093");
Color color2 = _colorFromHex("#b74093");
jeroen-meijer
  • 2,664
  • 2
  • 13
  • 16
Alvin Konda
  • 2,898
  • 1
  • 22
  • 22
  • 6
    Thansk 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')))` – Alvin Konda Dec 20 '19 at 20:21
26

To convert from a hexadecimal string to integer, do:

int hexToInt(String hex)
{
  int val = 0;
  int len = hex.length;
  for (int i = 0; i < len; i++) {
    int hexDigit = hex.codeUnitAt(i);
    if (hexDigit >= 48 && hexDigit <= 57) {
      val += (hexDigit - 48) * (1 << (4 * (len - 1 - i)));
    } else if (hexDigit >= 65 && hexDigit <= 70) {
      // A..F
      val += (hexDigit - 55) * (1 << (4 * (len - 1 - i)));
    } else if (hexDigit >= 97 && hexDigit <= 102) {
      // a..f
      val += (hexDigit - 87) * (1 << (4 * (len - 1 - i)));
    } else {
      throw new FormatException("Invalid hexadecimal value");
    }
  }
  return val;
}

Call example:

Color color = new Color(hexToInt("FFB74093"));
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Rockvole
  • 4,422
  • 3
  • 21
  • 27
24

There is another solution. If you store your color as a normal hexadecimal string and don't want to add opacity to it (leading "FF"):

  1. Convert your hexadecimal string to int To convert a hexadecimal string to an integer, do one of the following:

     var myInt = int.parse(hexString, radix: 16);
    

    or

     var myInt = int.parse("0x$hexString");
    

    as a prefix of 0x (or -0x) will make int.parse default to a radix of 16.

  2. Add opacity to your color via code

     Color color = new Color(myInt).withOpacity(1.0);
    
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Evgeny Kot
  • 286
  • 2
  • 4
19

This was the solution for me:

String hexString = "45a3df";
Color(int.parse("0xff${hexString}"));

It was the only way that didn't require additional steps.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Rio Weber
  • 2,757
  • 1
  • 20
  • 28
14

Use hexcolor for bringing hexadecimal colors to the Dart hexcolorPlugin:

hexcolor: ^2.0.3

Sample usage

import 'package:hexcolor/hexcolor.dart';
Container(
    decoration: new BoxDecoration(
        color: Hexcolor('#34cc89'),
    ),
    child: Center(
        child: Text(
            'Running on: $_platformVersion\n',
            style: TextStyle(color: Hexcolor("#f2f2f2")),
        ),
    ),
),
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Rudresh Narwal
  • 2,740
  • 3
  • 11
  • 21
13

In Flutter, to create a color from RGB with alpha, use:

return new Container(
  color: new Color.fromRGBO(0, 0, 0, 0.5),
);

How to use hexadecimal color:

return new Container(
  color: new Color(0xFF4286f4),
);
// 0xFF -> the opacity (FF for opaque)
// 4286f4 -> the hexadecimal color

Hexadecimal color with opacity:

return new Container(
  color: new Color(0xFF4286f4).withOpacity(0.5),
);

// Or change the "FF" value

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

For more, see the official documentation page, Color class - dart:ui library - Dart API.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Amit Prajapati
  • 13,525
  • 8
  • 62
  • 84
11

You can use this

Color getColorFromColorCode(String code){
  return Color(int.parse(code.substring(1, 7), radix: 16) + 0xFF000000);
}
David Buck
  • 3,752
  • 35
  • 31
  • 35
MD.FAISAL KABIR
  • 161
  • 1
  • 10
10

File utils.dart

///
/// Convert a color hex-string to a Color object.
///
Color getColorFromHex(String hexColor) {
  hexColor = hexColor.toUpperCase().replaceAll('#', '');

  if (hexColor.length == 6) {
    hexColor = 'FF' + hexColor;
  }

  return Color(int.parse(hexColor, radix: 16));
}

Example usage

Text(
  'Hello, World!',
  style: TextStyle(
    color: getColorFromHex('#aabbcc'),
    fontWeight: FontWeight.bold,
  )
)
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Michel
  • 26,600
  • 6
  • 64
  • 69
10

There isn't any need to use functions.

For example, to give a color to a container using colorcode:

Container
(
    color:Color(0xff000000)
)

Here the 0xff is the format followed by color code

Kamlesh
  • 5,233
  • 39
  • 50
10

Simple extension based on @Serdar answer https://stackoverflow.com/a/57943307/4899849

extension HexString on String {
  int getHexValue() => int.parse(replaceAll('#', '0xff'));
}

Usage:

'#b74093'.getHexValue()
Volodymyr
  • 1,192
  • 21
  • 42
7

Add this function in your file -


Color parseColor(String color) {
  String hex = color.replaceAll("#", "");
  if (hex.isEmpty) hex = "ffffff";
  if (hex.length == 3) {
    hex = '${hex.substring(0, 1)}${hex.substring(0, 1)}${hex.substring(1, 2)}${hex.substring(1, 2)}${hex.substring(2, 3)}${hex.substring(2, 3)}';
  }
  Color col = Color(int.parse(hex, radix: 16)).withOpacity(1.0);
  return col;
}

And use it like -

Container(
    color: parseColor("#b74093")
)
robben
  • 637
  • 1
  • 7
  • 14
7

The easiest way is to convert it into an integer. For example, #BCE6EB. You would add 0xFF and you would then remove the hashtag making it:

0XFFBCE6EB

Then let’s say you were to implement it by doing:

backgroundColor: Color(0xffbce6eb)

If you can only use a hexadecimal then I suggest using the Hexcolor package.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Safeer Abbas
  • 393
  • 4
  • 9
6

For general reference. There is a simpler way using the library Supercharged. Although you can use extension methods with all solutions mentioned, you find practical user library toolkit.

"#ff00ff".toColor(); // Painless hex to color
"red".toColor(); // Supports all web color names

Easier, right?

Supercharged

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Gauris Javier
  • 387
  • 4
  • 11
5

"#b74093"? OK...

To HEX Recipe

int getColorHexFromStr(String colorStr)
{
  colorStr = "FF" + colorStr;
  colorStr = colorStr.replaceAll("#", "");
  int val = 0;
  int len = colorStr.length;
  for (int i = 0; i < len; i++) {
    int hexDigit = colorStr.codeUnitAt(i);
    if (hexDigit >= 48 && hexDigit <= 57) {
      val += (hexDigit - 48) * (1 << (4 * (len - 1 - i)));
    } else if (hexDigit >= 65 && hexDigit <= 70) {
      // A..F
      val += (hexDigit - 55) * (1 << (4 * (len - 1 - i)));
    } else if (hexDigit >= 97 && hexDigit <= 102) {
      // a..f
      val += (hexDigit - 87) * (1 << (4 * (len - 1 - i)));
    } else {
      throw new FormatException("An error occurred when converting a color");
    }
  }
  return val;
}
Community
  • 1
  • 1
Nahuel Cabrera
  • 340
  • 1
  • 6
5

Use hexadecimal numbers with the fromRGB constructor:

Color.fromRGBO(0xb7, 0x40, 0x93, 1),
Adam
  • 2,800
  • 1
  • 13
  • 15
5

As the Color constructor does not support hexadecimal string, so we should find other alternatives.

There are several possibilities:

1- The first one is to create a small function that will allow you to convert a color hex-string to a Color object.

Code:

   Color colorFromHex(String hexColor) {
   final hexCode = hexColor.replaceAll('#', '');
   if (hexColor.length == 6) {
    hexColor = 'FF' + hexColor; // FF as the opacity value if you don't add it.
   }
  return Color(int.parse('FF$hexCode', radix: 16));
}

Usage:

 Container(
          color: colorFromHex('abcdff'),
          child: Text(
            'Never stop learning',
            style: TextStyle(color: colorFromHex('bbffffcc')),
          ),
        )

2- The second possibility is to use the supercharged package. Supercharged brings all the comfort features from languages like Kotlin to all Flutter developers.

Add the dependency supercharged: ^1.X.X (find recent version) to your project and start using Supercharged everywhere:

import 'package:supercharged/supercharged.dart';

Now ,transform any String to colors

Code :

"#ff00ff".toColor(); // Painless hex to color
"red".toColor(); // Supports all web color names

You can also use the hexcolor package which is also great.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Kab Agouda
  • 6,309
  • 38
  • 32
5

To use hex color code inside flutter you can simply use following trick:

Example :

Your color code : #F8485E

Now remove # and use following declaration:

Color(0xFFF8485E) //Add 0xFF and Replace # with your hex code

Happy Fluttering!

Pranav Dave
  • 393
  • 5
  • 7
4
import 'package:flutter/material.dart';
class HexToColor extends Color{
  static _hexToColor(String code) {
    return int.parse(code.substring(1, 7), radix: 16) + 0xFF000000;
  }
  HexToColor(final String code) : super(_hexToColor(code));
}

Import the new class and use it like this:

HexToColor('#F2A03D')
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
watchdog0x
  • 49
  • 1
3

You can click on Color Widget and it tells you with much deeper information what those letters stand for.

You can also use the Color.fromARGB() method to create custom colors which is much easier to me. Use the Flutter Doctor Color Picker website to pick any color you want for your Flutter application.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
eyoeldefare
  • 2,136
  • 1
  • 15
  • 25
3

I have created this Flutter extention function of String class.. kinda useful if you also hate 0xFFF

extension on String {
  Color parse() {
    var hexColor = this.replaceAll("#", "");
    if (hexColor.length == 6) {
      hexColor = "FF" + hexColor;
    }
    if (hexColor.length == 8) {
      return Color(int.parse("0x$hexColor"));
    }
  }
}

you can use to any hexadecimal color code string as follows...

'#bdbdbd'.parse() // this will return Color class object which you use in widget... 
abhi
  • 961
  • 9
  • 13
2

You can use the package from_css_color to get Color out of a hexadecimal string. It supports both three-digit and six-digit RGB hexadecimal notation.

Color color = fromCSSColor('#ff00aa')

For optimisation sake, create a Color instance once for each color and store it somewhere for later usage.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Alex Myznikov
  • 919
  • 9
  • 19
2

The best way is to use the flutter hex color plugin from pub.dev and the import the package.

import 'package:hexcolor/hexcolor.dart';

and then use that in this particular way.

Text( 
     'Running on: $_platformVersion\n',
      style: TextStyle(color: HexColor("#f2f2f2")),
    ),
Text(
      "Hex From Material  $textColor",
       style: TextStyle(color: ColorToHex(Colors.teal)),
    ),

particular plugin here.

MNBWorld
  • 529
  • 1
  • 5
  • 25
2

While the existing answer is correct, the solution is overcomplicated. Dart has simpler methods to convert hexadecimal strings to Colors.

This function converts a hex string to an integer

int hexToInteger(String hex) => int.parse(hex, radix: 16);

Usage:

final red = Color(hexToInteger('FFFF0000'));

You can also extend String to convert to a Color

extension StringColorExtensions on String {
  Color toColor() => Color(hexToInteger(this));
}

Usage:

final red = 'FFFF0000'.toColor();

You can read more about these functions in this blog post.

Christian Findlay
  • 6,770
  • 5
  • 51
  • 103
1

If you need a hexadecimal color desperately in your application, there is one simple step you can follow:

  1. Convert your hexadecimal color into RGB format simply from here.

  2. Get your RGB values.

  3. In Flutter, you have an simple option to use RGB color:

    Color.fromRGBO(r_value, g_value, b_value, opacity) will do the job for you.

  4. Go ahead and tweak O_value to get the color you want.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jithin Palepu
  • 596
  • 1
  • 7
  • 18
1

// call this line for set color
color: HexColor(HexColor.Primarycolor)

i have create a class HexColor and defile all color in this class. this is 100% working code

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);
   }

 static var Primarycolor="FF3E3F";

  static var Accentcolor="b74093";

  static var white="b74093";

static var black="b74093";

HexColor(final String hexColor) : super(_getColorFromHex(hexColor));
}
sarjeet singh
  • 461
  • 4
  • 10
1

I'm using this material_color_gen package it works like a charm

material_color_gen: ^2.0.0

Using :

import 'package:material_color_gen/material_color_gen.dart';
primarySwatch: Color(0xFFFF0000).toMaterialColor()

This is a HexColor example: #ff0000 Change # with 0xFF result is: 0xFFFF0000

Official link : https://pub.dev/packages/material_color_gen

Rachid Loukili
  • 623
  • 6
  • 15
1

if you want to use flutter hex color with opacity

just use. Color(0x800F1D41) for 50%, 80 is a declaration of 50%.

more details here

0

You can write a small console utility for converting a string:

import 'dart:convert';
import 'dart:io';

void main() {
  while (true) {
    var line = stdin.readLineSync(encoding: utf8);

    print(HexColor.fromHex(line!));
  }
}

class HexColor {
  static fromHex(String hexString) {
    final buffer = StringBuffer();
    if (hexString.length == 6 || hexString.length == 7) buffer.write('ff');
    buffer.write(hexString.replaceFirst('#', ''));
    return int.parse(buffer.toString(), radix: 16);
  }
}
David
  • 306
  • 4
  • 13