3

How can you add colours from Hex values in Flutter? For instance, I am trying the following:

Widget build(BuildContext context) {
  return Row(
    children: <Widget>[
      Expanded(
        child: Container(
          padding: EdgeInsets.only(left: 20.0),
          height: 100.0,
          decoration: BoxDecoration(
            color: Color.hex("#183451"),
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              Image.asset('assets/main_image.png'),
              // More widgets here
            ],
          ),
        ),
      ),
    ],
  );
}

But get the following error:

Error: The argument type 'color::Color' can't be assigned to the parameter type 'dart.ui::Color

This is using the "color" package: https://pub.dartlang.org/packages/color

If I use a MaterialColor it will work as anticipated:

color: Colors.blue

I guess I would need to create a MaterialColor, however these take an integer value and swatch. Would the Hex Value need to be converted from a string to an int? I guess looking for some code examples how to acheive this, if possible :)

Thanks in advance

Danny Brady
  • 1,895
  • 4
  • 20
  • 30

2 Answers2

13

You don't really need an external package to use custom colors.

Just use it like this Color(0xFF183451) , where the FF is the transparency , with 00 being transparent and FF being opaque.

hacksy
  • 830
  • 5
  • 14
  • Is there any way to use 50% or any % of these colors? Like something Color(0xFF183451)[50]? – Ankit Aug 12 '21 at 12:46
2
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;
}
Andrii Turkovskyi
  • 27,554
  • 16
  • 95
  • 105