参数类型“Function”无法分配给参数类型“void Function()”?零安全后

2024-02-21

我想实现制作一个抽屉,上面放有不同的物品,所以我正在为DrawerItems并使用构造函数将数据传递到主文件。但我收到以下错误onPressed功能:

"The argument type 'Function' can't be assigned to the parameter type 'void Function()'"
class DrawerItem extends StatelessWidget {
    
      final String text;
      final Function onPressed;
    
      const DrawerItem({Key key, this.text, this.onPressed}) : super(key: key);
    
      @override
      Widget build(BuildContext context) {
        return FlatButton(
          child: Text(
            text,
            style: TextStyle(
              fontWeight: FontWeight.w600,
              fontSize: 18.0,
            ),
          ),
          onPressed: onPressed,
        );
      }
    }

有人知道为什么吗?


更改您的代码以接受VoidCallback代替Function为了onPressed.
顺便一提VoidCallback只是简写void Function()所以你也可以将其定义为final void Function() onPressed;

更新的代码:

class DrawerItem extends StatelessWidget {
    
      final String text;
      final VoidCallback onPressed;
    
      const DrawerItem({Key key, this.text, this.onPressed}) : super(key: key);
    
      @override
      Widget build(BuildContext context) {
        return FlatButton(
          child: Text(
            text,
            style: TextStyle(
              fontWeight: FontWeight.w600,
              fontSize: 18.0,
            ),
          ),
          onPressed: onPressed,
        );
      }
    }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

参数类型“Function”无法分配给参数类型“void Function()”?零安全后 的相关文章

随机推荐