Home > database >  Dart null safety with if check
Dart null safety with if check

Time:12-17

I am use Dart Null Safety version

Have a widget:

enter image description here

itemBuilder expects a Widget type.

footer is Widget? type and will be null

Why Dart ignoring my null check? Also I only found one solution:

if (footer != null && index == data.length) {
    return footer ?? const SizedBox();
}

CodePudding user response:

Why Dart ignoring my null check?

Because when the following code executed:

Widget? footer;

...
if (footer != null && index == data.length) {
    return footer;
}

There is a probability that your footer is set to null from the other part of your code hence the error is shown.

You can add ! if you're completely sure that the footer won't be nulled for the rest of its life. So, you can use this:

if (footer != null && index == data.length) {
    return footer!;
}

but your solution much safer because it always check if footer not null:

if (footer != null && index == data.length) {
    // whenever footer is nulled, return SizedBox
    return footer ?? const SizedBox();
}

CodePudding user response:

Correct code:

final footer = this.footer;
if (footer != null && index == data.length) {
    return footer;
}

Why? Because subclass of this class can override footer getter. i.e.:

Widget get footer {
  if (Random().nextBool()) return null;
  else return super.footer;
}

So every call to footer could return null.

Personally, I always do '!'(if (footer != null) footer!) after check. Because providing getter with side effects is a large code smell.

CodePudding user response:

You can use this code snippet to check that a variable is null or not

a != null && [do something]
  • Related