将字符串值转换为flutter中的小部件

cig3rfwq  于 2023-02-09  发布在  Flutter
关注(0)|答案(2)|浏览(123)

我有颜色值颜色(0XFFDDDDDDD)作为字符串存储在我的数据库中。我想把它转换成颜色窗口小部件在Flutter。我该怎么做?Here is image of flutter color value picked from color picker
我尝试拆分字符串以删除Color()并获取0XFFDDDDDDD值,但没有成功。我希望能够使用此字符串值来着色值,如:容器(颜色:颜色(0XFFDDDDD))

w7t8yxp5

w7t8yxp51#

这应该行得通:

String s = "0xffdddddd";
Container(color: Color(int.parse(s)))
fcg9iug3

fcg9iug32#

这将给予你十六进制颜色字符串

String color = "Color(0XFFDDDDDD)";
 String hex = color.substring(0, color.length - 1);
 hex = hex.substring(6, hex.length);

将其解析为颜色:Color(int.parse(hex));
理想情况下,您的十六进制颜色也应该保存为一个纯十六进制颜色在数据库中,这样您就不必格式化字符串不必要的。
顺便说一句,如果解析不工作,试试这个扩展:

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

相关问题