I get the following error: The argument type 'void Function(String?)' can't be assigned to the parameter type 'void Function()?' when I this in my code:
void openNoteBox(String? docID) {}
...
***onPressed: openNoteBox //Error here***
...
onPressed: () => openNoteBox(docID), // it works here
...
This fixed it:
void openNoteBox({String? docID}) {}
...
***onPressed: openNoteBox, //error is gone here***
...
onPressed: () => openNoteBox(docID: docID),
...
but why would the previous one not work?
In the first code you defined a required positional parameter. To define an optional positional parameter, use this syntax:
void openNoteBox([String? docID]) {}
From the documentation on optional positional parameters:
Wrapping a set of function parameters in
[]
marks them as optional positional parameters.
In the second code you defined a named parameter, which by default is optional. From the documentation:
Named parameters are optional unless they’re explicitly marked as
required
.
Also note that you can't define both named parameters and optional positional parameters. From the documentation on parameters:
A function can have any number of required positional parameters. These can be followed either by named parameters or by optional positional parameters (but not both).