Home > Enterprise >  How to check if a function parameter is null
How to check if a function parameter is null

Time:10-27

I want to know if a function passed by the constructor is null or not, but when I check it, it doesn't recognize the function as null, even though I didn't pass anything as a parameter.

This is my widget:

const CropImageWidget({
    this.navBack,
    super.key,
  });

final Function? navBack;

Here is where I check if navBack is null or not:

if (widget.navBack == null) {
   Navigator.pop(context);
}
widget.navBack!();

The problem is that widget.navBack is never null.

I need to check if a function is or isn't passed in the constructor to execute function or to just pop the screen.

Solution: I thought the Navigator.pop(context) would return and not execute the code after it, however it executes the pop and then executes the function, which gives me the error. So, to make the code work I just did an If/else like this:

if (widget.navBack == null) {
    Navigator.pop(context);
} else {
    widget.navBack!();
}

CodePudding user response:

try this:

           final VoidCallback? navBack;

            onPressed: (){
              if(navBack == null){
             Navigator.pop(context);
              }
            }

CodePudding user response:

I thought the Navigator.pop(context) would return and not execute the code after it, however it executes the pop and then executes the function, which gives me the error. So, to make the code work I just did an If/else like this:

if (widget.navBack == null) {
    Navigator.pop(context);
} else {
    widget.navBack!();
}
  • Related