Flutter String 到 Icon 值

Gok*_*dar 6 flutter

如何在 Flutter 中将 String 值转换为 Icons 值,我从 json 获取 Icon 值作为字符串。

当我尝试使用该值时出现以下错误

error: The argument type 'String' can't be assigned to the parameter type 'IconData'. (argument_type_not_assignable at [hippo] lib\screens\dynamic_list.dart:71)
Run Code Online (Sandbox Code Playgroud)
{
  "page": 1,
  "MenuItems": [
    {
      "id": 419701,
      "icon": "MdiIcons.account",
      "name": "account"
    },
    {
      "id": 419702,
      "icon": "MdiIcons.currencyUsd",
      "name": "Funds"
    },
    {
      "id": 419703,
      "icon": "MdiIcons.home",
      "name": "home"
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*ary 7

一种方法是您可以将图像生成为字体图标(生成为字体)。将 ttf 文件保存在资产中。将 unicode 数据传递给 json(如“e90a”)。

例如:

Icon(IconData(int.parse('0x${e90a}',
    fontFamily: 'family name given in the link above'));
Run Code Online (Sandbox Code Playgroud)

  • 您好,我如何找到图标的 unicode 数据? (2认同)
  • Dart 有一个内置函数可以从 char 中获取 unicode 值,因此,例如,当您想要将井号/井号显示为图标时,您可以这样写: `Icon(IconData("#".codeUnitAt(0)) )` (2认同)

Muh*_*eel 6

您可以通过使用 Icon 类常量来实现。

Icon(IconData(61668, fontFamily: 'MaterialIcons'));
Run Code Online (Sandbox Code Playgroud)

查看更多 Icon 类常量:https : //api.flutter.dev/flutter/material/Icons-class.html#constants

https://api.flutter.dev/flutter/material/Icons-class.html#constants

  • 2020 年 6 月 24 日似乎有更新,其中这些代码不再与图标匹配:https://github.com/flutter/flutter/issues/75633 还有其他人遇到此问题吗? (2认同)