问题描述
过去当我用来提取带有按钮和 onpressed 方法的小部件时
我曾经用函数数据类型
的变量替换onpressed方法采用的回调函数但是现在当我尝试提取一个名为 RoundedButton 的小部件时 将Flutter 版本升级到 2.0.4 后,这是 Flutter 的最新稳定版本。
它给了我那个错误:
**The argument type 'Function' can't be assigned to the parameter type 'void Function()?'.**
这是在 onpressed: onpressed,
代码行下带有红线的代码:
class RoundedButton extends StatelessWidget {
final String title;
final Color color;
final Function onpressed;
RoundedButton(
{required this.onpressed,required this.color,required this.title});
@override
Widget build(BuildContext context) {
return Padding(
padding: EdgeInsets.symmetric(vertical: 16.0),child: Material(
color: color,borderRadius: BorderRadius.all(Radius.circular(30.0)),elevation: 5.0,child: MaterialButton(
onpressed: onpressed,minWidth: 200.0,height: 42.0,child: Text(
title,style: TextStyle(color: Colors.white),),);
}
}
解决方法
而不是它的旧类型:`
功能
我弄清楚了flutter 2.0.4中使用的onPressed方法的类型
它是`
VoidCallback?
导入 **dart:io**
库
使用 最后的 VoidCallback onPressed; //final void Function() onPressed;