乐闻世界logo
搜索文章和话题

How do i use hexadecimal color strings in flutter?

3个答案

1
2
3

In Flutter, you typically use the Color class to represent colors, which accepts an ARGB integer as a parameter. Hexadecimal color strings are typically represented in RGB or ARGB format, such as "#RRGGBB" or "#AARRGGBB", where AA is optional and represents transparency (alpha channel).

To use hexadecimal color strings, you need to convert them into a Flutter Color object. Here are the steps to do this:

  1. If the string does not include transparency (i.e., it has a length of 6 characters, such as "#RRGGBB"), you need to add the prefix 0xFF to indicate full opacity.
  2. Use Dart's int.parse function to convert the hexadecimal string into an integer.
  3. Create a Color object and pass the converted integer value to its constructor.

Here is an example:

dart
String hexColorStr = "#34A853"; // An example color string without transparency String hexColorStrWithAlpha = "#FF34A853"; // This string includes transparency (FF indicates full opacity) // If transparency is not included, add `0xFF` to use a fully opaque color hexColorStr = "0xFF" + hexColorStr.substring(1); // Convert the color string to an integer and create a Color object Color color = Color(int.parse(hexColorStr)); // If transparency is included, parse directly Color colorWithAlpha = Color(int.parse(hexColorStrWithAlpha.substring(1), radix: 16)); // Now you can use this color in Flutter, for example: Container( color: color, // or use colorWithAlpha child: ... );

Note that in Dart, hexadecimal numbers start with "0x", so when parsing, you need to remove the "#" from the string and replace it with "0x" (or directly add "0xFF" as the opacity prefix).

This is one method to use hexadecimal color strings in Flutter.

2024年6月29日 12:07 回复

The Color class requires an ARGB integer. Since you are trying to use it with RGB values, represent it as an integer and add the prefix 0xff.

dart
Color mainColor = Color(0xffb74093);

If you find this frustrating and still wish to use strings, you can extend Color and add a string constructor.

dart
class HexColor extends Color { static int _getColorFromHex(String hexColor) { hexColor = hexColor.toUpperCase().replaceAll("#", ""); if (hexColor.length == 6) { hexColor = "FF" + hexColor; } return int.parse(hexColor, radix: 16); } HexColor(final String hexColor) : super(_getColorFromHex(hexColor)); }

Usage

dart
Color color1 = HexColor("b74093"); Color color2 = HexColor("#b74093"); Color color3 = HexColor("#88b74093"); // If you wish to use ARGB format
2024年6月29日 12:07 回复

In Flutter, the Color class only accepts integers as parameters, or you can use the named constructors fromARGB and fromRGBO. Therefore, we simply need to convert the string #b74093 to an integer value. Additionally, we must account for the opacity, which is always required. The value FF represents full opacity (255), leaving us with 0xFF. Now, we can append the color string as follows:

dart
const color = const Color(0xffb74093); // Second `const` is optional in assignments.

The letters can be uppercase or lowercase:

dart
const color = const Color(0xFFB74093);

If you want to use opacity percentage values, you can replace the first value (also applicable to other color channels) with the corresponding value from this table: Hex Opacity Values

Extension Class

Starting from Dart 2.6.0, you can create an extension for the Color class to allow creating instances using hexadecimal color strings:

dart
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')}'; }

This method can also be declared in a mixin or class, but an extension is useful for implicit usage. Here's an example:

dart
void main() { final Color color = HexColor.fromHex('#aabbcc'); print(color.toHex()); print(const Color(0xffaabbcc).toHex()); }

Drawbacks of Using Hexadecimal Strings

Many other answers demonstrate how to dynamically create a Color instance from a hexadecimal string, as I did above. However, this approach means the color cannot be const. Ideally, you should assign the color as explained in the first part of this answer, which is more efficient when instantiating colors in large quantities—common in Flutter widgets.

2024年6月29日 12:07 回复

你的答案