Reputation: 1897
How can I convert a flutter Color
class instance into a hex string?
For example, I would like to convert Colors.blue
to what would be '#4286f4'
.
Usecase is letting the user choose a color and save it in the database as a hex color.
I have checked related questions and they are for converting the other way around.
Upvotes: 54
Views: 33744
Reputation: 356
Since latest versions of flutter deprecated the .value, .red, .green, .blue
usage, here is a very similar implementation of previous answers with the updated api.
extension HexColor on Color {
/// Converts a hexadecimal string to a [Color] object.
///
/// The [hexString] should be in the format "aabbcc" or "ffaabbcc" with an
/// optional leading "#". Returns `null` if the input is `null` or invalid.
static Color? fromHex(String? hexString) {
if (hexString == null) {
return null;
}
try {
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));
} catch (e) {
return null;
}
}
/// Converts this [Color] object to a hexadecimal string representation.
///
/// The returned string is in the format "#aarrggbb" if [leadingHashSign] is
/// `true`, otherwise "aarrggbb".
String toHex({bool leadingHashSign = true}) {
final hexA = (a * 255).round().toRadixString(16).padLeft(2, '0');
final hexR = (r * 255).round().toRadixString(16).padLeft(2, '0');
final hexG = (g * 255).round().toRadixString(16).padLeft(2, '0');
final hexB = (b * 255).round().toRadixString(16).padLeft(2, '0');
return '${leadingHashSign ? '#' : ''}$hexA$hexR$hexG$hexB';
}
}
Hope it works for you!
Upvotes: 4
Reputation: 141
With .value
, .red
, .green
, .blue
attributes being deprecated in latest dart UI library(as of Oct 2024), you can use below code:
extension HexColorExt on Color {
/// Convert to HTML compatible hex string.
/// Note, alpha channel is at the end in HTML
/// Dart: 0xAARRGGBB
/// HTML: #RRGGBBAA
String toHtmlHexStr({required bool withAlpha}) {
int nonAlpha = toARGB32() & 0xFFFFFF;
if (!withAlpha) {
return '#${nonAlpha.toRadixString(16).padLeft(6, '0')}';
}
int alpha = (toARGB32() & 0xFF000000) >> 24;
return '#${nonAlpha.toRadixString(16).padLeft(6, '0')}${alpha.toRadixString(16).padLeft(2, '0')}';
}
}
Test cases:
import 'dart:ui';
import 'package:test/test.dart';
import 'color_ext.dart';
void main() {
group('HexColorExt', () {
test('toHtmlHexStr without alpha', () {
const color = Color(0xFFAABBCC);
final hexString = color.toHtmlHexStr(withAlpha: false);
expect(hexString, '#aabbcc');
});
test('toHtmlHexStr with alpha', () {
const color = Color(0x80AABBCC);
final hexString = color.toHtmlHexStr(withAlpha: true);
expect(hexString, '#aabbcc80');
});
test('toHtmlHexStr with full opacity', () {
const color = Color(0xFFAABBCC);
final hexString = color.toHtmlHexStr(withAlpha: true);
expect(hexString, '#aabbccff');
});
test('toHtmlHexStr with zero opacity', () {
const color = Color(0x00AABBCC);
final hexString = color.toHtmlHexStr(withAlpha: true);
expect(hexString, '#aabbcc00');
});
test('toHtmlHexStr with different color', () {
const color = Color(0x12345678);
final hexString = color.toHtmlHexStr(withAlpha: true);
expect(hexString, '#34567812');
});
});
}
Upvotes: -1
Reputation: 81
Improved Code:
extension HexColor on Color {
String _generateAlpha({required int alpha, required bool withAlpha}) {
if (withAlpha) {
return alpha.toRadixString(16).padLeft(2, '0');
} else {
return '';
}
}
String toHex({bool leadingHashSign = false, bool withAlpha = false}) =>
'${leadingHashSign ? '#' : ''}'
'${_generateAlpha(alpha: alpha, withAlpha: withAlpha)}'
'${red.toRadixString(16).padLeft(2, '0')}'
'${green.toRadixString(16).padLeft(2, '0')}'
'${blue.toRadixString(16).padLeft(2, '0')}'
.toUpperCase();
}
Usage:
pickerColor.toHex(withAlpha: true);
Upvotes: 5
Reputation: 343
This is my favorite way of handling color to string conversions. I use this really simple extension class.
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 ? '#' : ''}'
'${red.toRadixString(16).padLeft(2, '0')}'
'${green.toRadixString(16).padLeft(2, '0')}'
'${blue.toRadixString(16).padLeft(2, '0')}'
'${alpha.toRadixString(16).padLeft(2, '0')}';
}
Upvotes: 5
Reputation: 4038
In flutter if AA
is the alpha value in hex, RR
the red value in hex, GG
the green value in hex, and BB
the blue value in hex, a color can be expressed as const Color(0xAARRGGBB)
just remove the leading two symbols to get HEX value. RRGGBB
Upvotes: 0
Reputation: 404
Though the question is converting Color to Hex, if you want to store and retrieve Color information, I've used like this.
Save color data as int. Colors.blue.value
Retrieve data as int and pass it to Color class Color(savedInt)
Upvotes: -2
Reputation: 5811
This is what I'm using:
extension ColorX on Color {
String toHexTriplet() => '#${(value & 0xFFFFFF).toRadixString(16).padLeft(6, '0').toUpperCase()}';
}
Sample outputs: #00FFFF
or #FF69B4
This code also makes sure that alpha is omitted (@bakua's comment)
Some Flutter source code inspiration: util.dart, painting.dart
Upvotes: 13
Reputation: 13247
You can add an extension to Color
class to get HexString from the Color object itself directly.
extension HexColor on Color {
/// 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')}';
}
Color color = Colors.blue ;
print(color.toHex());
Upvotes: 15
Reputation: 657937
You can convert the value
property (includes alpha) or the individual red
, green
, and blue
properties to Hex using int.toRadixString(16)
:
var myColor = Colors.blue;
var hex = '#${myColor.value.toRadixString(16)}';
Upvotes: 100