Using Hex Color Strings in Flutter

Last reviewed by Frank Treacy
with Flutter 1.7.8

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 how do we convert an 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"));
  }
}

It takes a 6 (no alpha channel) or 8 (with alpha channel) character string, with or without the # prefix.

So what is this FF business all about?

0xFF is the hexadecimal notation of the integer 255, which corresponds to 100% opacity in the alpha channel!

By default, Dart creates colors with 0% opacity (i.e. transparent) which is the exact opposite of CSS (and very strange!)

For example, Color(0xBFEB91) will yield an invisible color as it’s not prefixed with FF.

As a utility class

// lib/util/color_utils.dart

import 'package:flutter/material.dart' show Color;

class HexColor extends Color {

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

  HexColor(final String hexColor) : super(_getColorFromHex(hexColor));
}

And simply use it like:

// lib/main.dart

import 'package:flutter/material.dart';
import 'util/color_utils.dart' show HexColor;

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Welcome to Flutter',
      home: Scaffold(
        appBar: AppBar(
          title: Text('Welcome to Flutter'),
        ),
        body: Center(
          child: Text(
            'Hello World',
            style: TextStyle(backgroundColor: HexColor('#bfeb91')), // or 'bfeb91', or 'ffbfeb91'
          ),
        ),
      ),
    );
  }
}

Finally, the result:

screenshot

The best from the Flutter-verse in 3 minutes or less? Join Snacks!

Delivered twice monthly. No link walls. No spam. EVER.