【问题标题】:Flutter set Colors from string variable [duplicate]Flutter从字符串变量中设置颜色[重复]
【发布时间】:2021-01-25 21:15:20
【问题描述】:

我有一个动态变量,它将由一些颜色启动

String bgColor = "#f8d547";

我想从那个变量中设置这个颜色属性

decoration: BoxDecoration(
  color: bgColor,
),

我怎样才能做到这一点? 谢谢。

【问题讨论】:

标签: flutter dart


【解决方案1】:

颜色: 颜色(int.parse(bgColor.replaceAll('#', '0x')));

【讨论】:

  • 我做了,但它没有改变..
【解决方案2】:

How do I use hexadecimal color strings in Flutter? 的副本

请去那里有详细的答案,反正这里就是你想要的。

你必须创建一个新函数,它可以作为 Color 的扩展来创建:

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

使用它:

final Color color = HexColor.fromHex('#aabbcc');

【讨论】:

  • 我找到了一个简短的代码,谢谢你的回答!!
猜你喜欢
  • 2013-02-10
  • 1970-01-01
  • 1970-01-01
  • 2021-04-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-02
  • 2012-06-03
相关资源
最近更新 更多