目录

avoid_init_to_null

目录
Stable
Recommended
Fix available

Don't explicitly initialize variables to null.

Details

#

From Effective Dart:

DON'T explicitly initialize variables to null.

If a variable has a non-nullable type or is final, Dart reports a compile error if you try to use it before it has been definitely initialized. If the variable is nullable and not const or final, then it is implicitly initialized to null for you. There's no concept of "uninitialized memory" in Dart and no need to explicitly initialize a variable to null to be "safe". Adding = null is redundant and unneeded.

BAD:

dart
Item? bestDeal(List<Item> cart) {
  Item? bestItem = null;

  for (final item in cart) {
    if (bestItem == null || item.price < bestItem.price) {
      bestItem = item;
    }
  }

  return bestItem;
}

GOOD:

dart
Item? bestDeal(List<Item> cart) {
  Item? bestItem;

  for (final item in cart) {
    if (bestItem == null || item.price < bestItem.price) {
      bestItem = item;
    }
  }

  return bestItem;
}

Enable

#

To enable the avoid_init_to_null rule, add avoid_init_to_null under linter > rules in your analysis_options.yaml file:

analysis_options.yaml
yaml
linter:
  rules:
    - avoid_init_to_null

If you're instead using the YAML map syntax to configure linter rules, add avoid_init_to_null: true under linter > rules:

analysis_options.yaml
yaml
linter:
  rules:
    avoid_init_to_null: true