How to convert HexColor to Flutter Color?

How to use HexColor in Flutter

If you are designing an app in Flutter, you may have trouble thinking as to how to convert HexColor to Flutter color. While there is a package that provides a solution to this problem, it’s advisable to use a minimum number of packages.

In Flutter the Color class only accepts hexadecimal values. The HexColor that we want to convert is also an hexadecimal string. Now there are two parameters to a color:

  1. RGB values
  2. Opacity of the color
Image showing the composition of the Color object, first part is the opacity and the second part is RGB values.
Image showing the composition of the Color object

The RGB (#RRGGBB) values received from the Hex String will be same. The opacity in the Color object is represented using 0x where, FF represents 100% opacity and 00 represents 0% opacity, you can see the other values here. We can also set the opacity later using the .withOpacity(double) where opacity value can range from 0 to 1.

Image showing how to convert HexColor to Color object in Flutter. First example shows Color with 100% opacity and seconds shows 50% opacity.
Image showing how to convert HexColor to Color object in Flutter

In the above image you can see, in the second Color we have 50% opacity so we have used 0x80 representing 50% opacity. We can also acheive the same result using 0xFF and using withOpacity(0.5) function.

Code for Copy Paste

import 'package:flutter/material.dart';

//Color with 100% opacity
Color color = const Color(0xFF50A7C2);

//Color with 50% opacity
Color color2 = const Color(0x8000C3FF);
//OR
Color color3 = Color(0xFF00C3FF).withOpacity(0.5);

So now if you see any HexColor check it’s opacity and RGB values. Now you can easily use it as a Flutter Color without any extra packages. If you still have any queries you can let me know in the comments down below. If you are new to Flutter check my post on how to install flutter on windows?

Leave a Reply

Your email address will not be published.

Previous Post
How to Create Collection Within Docs Flutter

Flutter: How to add Sub-Collection in Document? Firebase

Next Post

Flutter: How to Reduce the number of imports?

Related Posts