0

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!();
}
3
  • what is your error ? how do you call your cropImageWidget ? Commented Oct 26, 2022 at 15:19
  • 1
    actually you can answer to your own question. do not put the answer in the question section. to help other people find the answer who has same issue later Commented Oct 26, 2022 at 15:27
  • Thanks for the tip! Posted the answer below! Commented Oct 26, 2022 at 15:59

2 Answers 2

2

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!();
}
Sign up to request clarification or add additional context in comments.

Comments

0

try this:

           final VoidCallback? navBack;

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

2 Comments

This didn't work. I think I have found the 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.
it works for me. I run the code before posting. it might be a problem with your linter.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.