[colors] How do I use hexadecimal color strings in Flutter?

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.

This question is related to colors dart flutter

The answer is


if you want to use hex code of color which is in this format #123456 then it is very easily be used, create A variables of type Color and assign the following values to it.

Color myHexColor = Color(0xff123456) 

// her you notice I use the 0xff and that is opacity or transparency of the color 
// and you can also change these value .

use myhexcolor and you are ready to go .

if you want to change the opacity of color direct from the hex code then change the ff value in 0xff to the respectively value from the table below.

Hex 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

The Color class expects an ARGB integer. Since you try to use it with 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

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


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

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 .


The most 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 lets 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 https://pub.dev/packages/hexcolor


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

Don't know why this is being downed, this was the solution for me.
Only way that didn't require additional steps


"#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;
}

Use hexcolor for bringing hex colors to dart hexcolorPlugin

hexcolor: ^1.0.4

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")),
            ),
          ),
        ),

To convert from hexadecimal String to int, 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"));

In Flutter it create a color from RGB with alpha, use

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

How to use hex-color:

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

Hex-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 follow official link https://api.flutter.dev/flutter/dart-ui/Color-class.html


Easy way :

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

Usage:

Container(
    color: Color(int.parse(color)),
)

You can click on Color Widget and it tells you in much deeper information how those letters stand for. You can also use Color.fromARGB() method to create custom colors which is much easier to me. Use Flutter Doctor Color Picker website to pick any color you want for your flutter application.


How to use Hex Color Code #b74093 in Flutter

Simply remove the # sign from hex color code and ad 0xff with color code inside 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

Hexa Colors Example with all opacity types on Dartpad

enter image description here


I missed the obvious answer using hex numbers for the fromRGB constructor:

Color.fromRGBO(0xb7, 0x40, 0x93, 1),

No need functions

For example to give color to a container using colorcode

Container (

color:Color(0xff000000)

)

Here the 0xff is the format followed by color code


Unfortunately, the Color class constructor in Flutter does not accept a simple hexadecimal string (like #bfeb91 in CSS).

Instead, it requires an integer like 0xFFBFEB91.

So here is we convert a hex string to an integer

A simple function

Give this function a hex string and it will return you a Color!

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

Use it like this

Text(
  'Hello World',
  style: TextStyle(backgroundColor: _getColorFromHex('ff00aa')), // or 'bfeb91', or 'ffbfeb91'
),

As a String extension

Leveraging the power of Dart extensions we can augment String with a function that returns a Color:

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

Use it like this

Text(
  'Hello World',
  style: TextStyle(backgroundColor: '#bfeb91'.toColor()), // or 'bfeb91', or 'ffbfeb91'
),

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 :)


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

  1. Convert your Hex 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 tweek O_value to get the color you want.


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,
  )
)

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")
)

You can use this

Color getColorFromColorCode(String code){
  return Color(int.parse(code.substring(1, 7), radix: 16) + 0xFF000000);
}

There is another solution. If you store your color as normal hex string and don't want to add opacity to it (leading FF): 1) Convert your hex string to int To convert a hex-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 radix of 16.

2) Add opacity to your color via code

Color color = new Color(myInt).withOpacity(1.0);

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')


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

Color color = fromCSSColor('#ff00aa')

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