【问题标题】:Passing the icon name inside a widget to a variable将小部件内的图标名称传递给变量
【发布时间】:2021-12-22 10:20:48
【问题描述】:

如何将图标直接传递给抽象类 Widget extends ?我正在尝试创建此小部件,但它不支持我将图标名称放在字符串中并将其传递到图标(图标)中

              buildTextFormField(
              "Email teste", emailController, "usuario@imodulo.com",
              ),

    
Widget buildTextFormField(
  String label,
  TextEditingController c,
  String hintText,
  String icone,
) {
  return TextFormField(
    controller: c,
    autofocus: true,
    obscureText: true,
    keyboardType: TextInputType.emailAddress,
    style: TextStyle(color: Colors.white, fontSize: 16),
    decoration: InputDecoration(
      labelText: label,
      **prefixIcon: Icon(Icons.'$icone'),**
      hintText: hintText,
      labelStyle: TextStyle(color: Colors.white),
    ),
  );
}

【问题讨论】:

  • 为什么不直接将其传递为IconData

标签: flutter widget icons


【解决方案1】:

如果您查看Icons,您会发现它们只是字体的索引。所以,实际上图标并没有真正的“名称”,而是有数字。

这是一个随机的例子:

  static const IconData checklist = IconData(0xe15b, fontFamily: 'MaterialIcons');

因此,与其尝试使用名称“清单”来实例化图标,不如使用其编号 0xe15b

您本来打算将图标的名称存储在哪里(数据库?后端?),而不是存储一个数字,您的代码变成:

  prefixIcon: Icon(IconData(icone, fontFamily: 'MaterialIcons')),

【讨论】:

    【解决方案2】:

    我传递了一个iconData参数

    Widget buildTextFormField(
      String label,
      TextEditingController c,
      String hintText,
      **IconData icone,**
    ) {
      return TextFormField(
        controller: c,
        keyboardType: TextInputType.emailAddress,
        style: TextStyle(color: Colors.white, fontSize: 16),
        decoration: InputDecoration(
          labelText: label,
          **prefixIcon: Icon(icone),**
          hintText: hintText,
          labelStyle: TextStyle(color: Colors.white),
        ),
      );
    }
    

    【讨论】:

    • 您已经接受了另一个分析器,因此无需自己回答。我猜您想根据该答案展示您的解决方案以帮助其他人,这很好。要么将其写为已接受答案的评论,要么将其放在问题的末尾。请注意添加一个很好的解释,因为当前的解释不容易理解。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-21
    • 1970-01-01
    • 1970-01-01
    • 2020-12-11
    • 1970-01-01
    • 1970-01-01
    • 2014-08-13
    相关资源
    最近更新 更多