Reputation: 1223
I have a refactored widget which has an onPressed
. But whenever I try to access that function, I get this error :
The argument type Function? can't be assigned to the parameter type void Function()?
Here's the code for the refactored widget:
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();
},
),
],
);
}
}
Please someone explain the reason for this problem. Any help will be appreciated.
Upvotes: 1
Views: 776
Reputation: 386
It's stating that an argument of type Function? is different from type void Function()?. This is because a parameter of type Function? is quite different from that of type void Function()? since the former can have any return value but the later explicitly returns non (note: non is different from null).
To solve this issue: try changing the declaration Function? at the above code from Function? to void Function()?.
like so:
class DialogBox extends StatelessWidget {
const DialogBox(
{@required this.contentTitle, @required this.labelText,
this.onpressed});
final String? contentTitle;
final String? labelText;
final void Function()? onpressed;
...
}
Upvotes: 2
Reputation: 5736
You need to use Function()?
data-type instead of Function?
for onpressed
variable.
final Function()? onpressed;
Also, remove ;
and put ,
in following line:
onPressed: onpressed,
Upvotes: 1