0

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();
}
Leonid Veremchuk
  • 1,952
  • 15
  • 27

3 Answers3

1

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.

Alexander Farkas
  • 529
  • 3
  • 11
1

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();
}
ישו אוהב אותך
  • 28,609
  • 11
  • 78
  • 96
  • Your explanation is not right. If you declare footer as final (prevent any modification), the error would still be there. – Alexander Farkas Dec 16 '21 at 15:23
  • @AlexandrFarkas: No final code in OP question. `Although a final object cannot be modified, its fields can be changed. In comparison, a const object and its fields cannot be changed: they’re immutable.` https://dart.dev/guides/language/language-tour#final-and-const See https://stackoverflow.com/questions/50431055/what-is-the-difference-between-the-const-and-final-keywords-in-dart – ישו אוהב אותך Dec 16 '21 at 15:40
0

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

a != null && [do something]
gtr Developer
  • 2,369
  • 16
  • 12