【问题标题】:The argument type 'Icon' can't be assigned to the parameter type 'IconData in FlutterFlutter 中的参数类型“Icon”不能分配给参数类型“IconData”
【发布时间】:2021-07-22 05:39:38
【问题描述】:

我是 Flutter 的新手。我的应用程序中有可扩展列表。我在将图标分配给可扩展列表的标题时遇到问题。标题分配好。我正在使用它来要求所需的数据:

class ExpandableListItem {
  bool isExpanded;
  final String header;
  final String body;
  final Icon icon; // icon problem

  ExpandableListItem(
      {this.isExpanded: false,
      required this.header,
      required this.body,
      required this.icon});
}

之后我传递所需的参数,如下所示:

ExpandableListItem(
     header: 'Факультеты',
     body: 'news',
     icon: Icon(
       Icons.ac_unit,
       color: Colors.red,
     ),
   ),

当我用它把它分配给标题时,我用这个:

return Row(
                          mainAxisAlignment: MainAxisAlignment.start,
                          children: [
                            Icon(
                              item.icon
                            ),
                            SizedBox(width: 8),
                            Text(
                              item.header,
                              style: MainTheme.lightTheme.textTheme.headline2,
                            )
                          ],
                        );

这就是问题所在。我的错误是

“参数类型'Icon'不能分配给参数类型'IconData?'”。我该如何解决这个错误?

【问题讨论】:

  • item.icon 已经是 Icon 的类型
  • ?没看懂
  • 直接使用不带图标小部件,在行小部件中传递为:item.icon

标签: flutter dart


【解决方案1】:

这里的问题是,在ExpandableListItem class 中,您有一个Icon 类型的字段,它已经是一个图标小部件。因此,在您的 Row 小部件中,您不需要添加/创建新的图标小部件。

相反,您可以直接将 item.icon 用作 Icon 小部件。

return Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: [
                          item.icon
                        ,
                        SizedBox(width: 8),
                        Text(
                          item.header,
                          style: MainTheme.lightTheme.textTheme.headline2,
                        )
                      ],
                    );

【讨论】:

    【解决方案2】:
    
    class ExpandableListItem {
      bool isExpanded;
      final String header;
      final String body;
      final Widget icon; 
    }
    
    ExpandableListItem(
         header: 'Факультеты',
         body: 'news',
         icon: Icon(
           Icons.ac_unit,
           color: Colors.red,
         ),
       ),
    
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        item.icon,
        SizedBox(width: 8),
        Text(
          item.header,
          style: MainTheme.lightTheme.textTheme.headline2,
        )
      ],
    );
    

    【讨论】:

    • 如果他必须通过自定义颜色和尺寸怎么办?这是完全不推荐的!!
    • @OMiShah 所以而不是 Icon 作为数据类型更好地使它成为 final Widget icon
    • 无需更改它的小部件类型。只需在行小部件中直接使用 item.icon,而无需使用图标小部件包装 item.icon。
    猜你喜欢
    • 2020-01-23
    • 2022-12-04
    • 2021-12-22
    • 2022-01-23
    • 2021-10-17
    • 2021-12-15
    • 2019-11-17
    • 2021-07-06
    • 1970-01-01
    相关资源
    最近更新 更多