CallBack Function with null safety
1,015
If this function is required
just make the parameter required and the language will enforce you to always pass a function to the constructor of googleMapComponent
class googleMapComponent extends StatefulWidget {
Function(LatLng pos) OnPositionChangeCallback;
googleMapComponent({required this.OnPositionChangeCallback,})
Otherwise make the function nullable with the ?
keyword.
this is the final Answer to this question
final Function(LatLng pos)? OnPositionChangeCallback;
![Ardeshir ojan](https://i.stack.imgur.com/3DB5x.jpg?s=256&g=1)
Author by
Ardeshir ojan
Updated on December 30, 2022Comments
-
Ardeshir ojan over 1 year
I have a widget like this
class googleMapComponent extends StatefulWidget { Function(LatLng pos) OnPositionChangeCallback; googleMapComponent({ this.OnPositionChangeCallback,})
using nullsafety i get this error
The parameter 'OnPositionChangeCallback' can't have a value of 'null' because of its type, but the implicit default value is 'null'.
I know using required will fix it but I don't want it to be required
-
Darshan about 3 yearsYou can use
Function(LatLang? pos)
to allow null values or use the!
operator when passing values. -
Ardeshir ojan about 3 years@DarShan the first solution doesn't work and for the second one i don't want to send value because there is a lot of CallBack functions for this widget
-
-
Ardeshir ojan about 3 yearsno, it is not required and for the second solution you mean like this Function(LatLang? pos) if yes no it doesn't work either
-
croxx5f about 3 yearsThe whole function should be marked as nullable ` Function(String pos) OnPositionChangeCallback` ,not just its parameter. Just remember to always check if its not null before usage. Was that what you were looking for @Ardeshirojan?
-
Ardeshir ojan about 3 yearsyes, this is correct thank you.i will update your answer with the final answer