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;
Share:
1,015
Ardeshir ojan
Author by

Ardeshir ojan

Updated on December 30, 2022

Comments

  • Ardeshir ojan
    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
      Darshan about 3 years
      You can use Function(LatLang? pos) to allow null values or use the ! operator when passing values.
    • Ardeshir ojan
      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
    Ardeshir ojan about 3 years
    no, 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
    croxx5f about 3 years
    The 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
    Ardeshir ojan about 3 years
    yes, this is correct thank you.i will update your answer with the final answer