Flutter/Dart: Convert HEX color string to Color?

2019-03-04 00:21发布

问题:

Our database has colors saved as a String like "#AABBCC" and so I'm basically looking for a function like this: Color.parseColor("#AABBCC"); for Flutter

The Color class requires something like this Color(0xFF42A5F5) so I need to convert "#AABBCC" to 0xFFAABBCC

回答1:

/// Construct a color from a hex code string, of the format #RRGGBB.
Color hexToColor(String code) {
  return new Color(int.parse(code.substring(1, 7), radix: 16) + 0xFF000000);
}


回答2:

I ended up doing it this way:

hexStringToHexInt(String hex) {
  hex = hex.replaceFirst('#', '');
  hex = hex.length == 6 ? 'ff' + hex : hex;
  int val = int.parse(hex, radix: 16);
  return val;
}


回答3:

A simple string replacement would get it in the right syntax:

String html_colour = '#AAABBCC';
String fixed_colour = html_colour.replace(new RegExp(r'#'), '0xFF');

That should do it.