Skip to content

Instantly share code, notes, and snippets.

@morphingcoffee
Created November 5, 2021 23:24
Show Gist options
  • Save morphingcoffee/5220e47a86ac2c06bba2d89586a7d8c5 to your computer and use it in GitHub Desktop.
Save morphingcoffee/5220e47a86ac2c06bba2d89586a7d8c5 to your computer and use it in GitHub Desktop.
Dart extension for converting hex string to Color with ease
import 'dart:ui';
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 ? '#' : ''}'
'${alpha.toRadixString(16).padLeft(2, '0')}'
'${red.toRadixString(16).padLeft(2, '0')}'
'${green.toRadixString(16).padLeft(2, '0')}'
'${blue.toRadixString(16).padLeft(2, '0')}';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment