我有一个重构的小部件,它有一个 onPressed 属性。但是每当我尝试访问该功能时,我都会收到此错误:
参数类型“函数?”不能分配给参数类型 'void Function()?'
这是重构小部件的代码:
class DialogBox extends StatelessWidget {
const DialogBox(
{@required this.contentTitle, @required this.labelText, this.onpressed});
final String? contentTitle;
final String? labelText;
final Function? onpressed;
@override
Widget build(BuildContext context) {
return new AlertDialog(
title: Text(
contentTitle!,
style: TextStyle(
color: Theme.of(context).colorScheme.secondary,
),
),
content: new SingleChildScrollView(
child: ListBody(
children: <Widget>[
TextFormField(
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: labelText,
),
keyboardType: TextInputType.text,
),
],
),
),
actions: [
new TextButton(
child: new Text(
'Confirm',
style: TextStyle(
color: Theme.of(context).colorScheme.secondary,
),
),
onPressed:
onpressed, //getting the error here.
),
new TextButton(
child: new Text(
'Cancel',
style: TextStyle(
color: Theme.of(context).colorScheme.secondary,
),
),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
}
}
请有人解释这个问题的原因。任何帮助将不胜感激。
答案 0 :(得分:2)
它是说函数类型的参数?与类型 void Function()? 不同。这是因为函数类型的参数?与 void Function() 类型完全不同?因为前者可以有任何返回值,但后者显式返回 non(注意:non 与 null 不同)。
要解决此问题:尝试更改声明函数?在上面的函数代码中?到 void Function()?.
像这样:
class DialogBox extends StatelessWidget {
const DialogBox(
{@required this.contentTitle, @required this.labelText,
this.onpressed});
final String? contentTitle;
final String? labelText;
final void Function()? onpressed;
...
}
答案 1 :(得分:1)
您需要对 Function()?
变量使用 Function?
数据类型而不是 onpressed
。
final Function()? onpressed;
此外,删除 ;
并将 ,
放在以下行中:
onPressed: onpressed,