首页 > 解决方案 > 我想在 Flutter 中使用来自 firebase 的十六进制代码

问题描述

我是 Firebase 的新手,我终于从 Firebase 获得了数据。我使用颜色,每张卡片都有一个颜色和颜色编号。

我在 Firebase 中有:一个字段 colorCode,它是一个字符串,并且有一个值 '0xFFFFB142'

在 Flutter 中,我尝试这样做:

final int colorCode = list[index]['colorCode'].hashCode;

                            Container(
                              height: 25.0,
                              width: 25.0,
                              color: Color(colorCode),
                            ),

我没有失败,但我看不到颜色。

它必须是 int,但它是字符串代码中的十六进制。当我在 Firebase 中尝试一个 int 时,我失败了,因为它是十六进制的。

更新:谢谢大家到目前为止的帮助!我自己在 Firebase 中输入了代码。它和你通常放在那个地方一样,比如颜色:颜色(0xFFFFB142),其中FFB142是颜色#FFB142 在Firebase中我使用了字符串,因为不允许使用int或纯代码。使用我的代码,当我打印它时:它得到 171924876,这不是正确的颜色代码。

我试过这个:

                    final dynamic colorCode =
                        list[index]['colorCode'].toString();

                    print(colorCode); // the right color code is printend: 0xFFFFB142

当我把它放进去时:

                            Container(
                              height: 25.0,
                              width: 25.0,
                              color: Color(0xFFFFB142),

它工作正常,但我在 Firebase 中为每个项目都有另一个颜色代码。

我发现收到此错误消息很奇怪,因为我不想要一个 int ,而是像 0xFFFFB142 这样的颜色代码

 type 'String' is not a subtype of type 'int'

希望你能帮我!

标签: firebaseflutterhexbackground-colorhashcode

解决方案


您可以使用截断0x并将其余部分解析为十六进制的函数。

Color convertToColor(String prefixedHex) => Color(int.parse(
      prefixedHex.substring(2),
      radix: 16,
    ));

推荐阅读