Contents
Contents

Don't explicitly initialize variables to null.

This rule is available as of Dart 2.0.0.

Rule sets: recommended, flutter

This rule has a quick fix available.

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;
}

Usage

#

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