'The argument type 'Function?' can't be assigned to the parameter type 'void Function()?'
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.
Solution 1:[1]
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,
Solution 2:[2]
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;
...
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Tirth Patel |
Solution 2 | John Oyekanmi |