Rules / Style / unnecessary-nullable-for-final-variable-declarations

unnecessary-nullable-for-final-variable-declarations

lint/style/unnecessary-nullable-for-final-variable-declarations
Same as unnecessary_nullable_for_final_variable_declarations · Dart lints

Flags a final or const variable given a nullable type but initialized to a provably non-null value.

A final int? x = 3; can never hold null: it is initialized once, at the declaration, to a value that is obviously non-null. The ? widens the static type for no reason, forcing needless null checks at every use. The rule is deliberately conservative about "provably non-null" — only literals (numbers, strings, booleans, collections, records), constructor invocations, and function expressions qualify; anything whose value flows from another binding is left alone. It applies to final/const top-level variables, static fields, and local variables. Drop the ? from the declared type.

Invalid

example.dartdart
final int? a = 3;
const String? b = 'x';

class C {
  static final int? sf = 5;

  void method() {
    final double? d = 1.5;
    final List<int>? list = [1, 2];
    final Map<String, int>? m = {'a': 1};
    final bool? flag = true;
    print('$d $list $m $flag');
  }
}
Unnecessary nullable type for a final variable declaration.
1final int? a = 3;
Unnecessary nullable type for a final variable declaration.
1final int? a = 3;
2const String? b = 'x';
Unnecessary nullable type for a final variable declaration.
4class C {
5 static final int? sf = 5;
Unnecessary nullable type for a final variable declaration.
7 void method() {
8 final double? d = 1.5;
Unnecessary nullable type for a final variable declaration.
8 final double? d = 1.5;
9 final List<int>? list = [1, 2];
Unnecessary nullable type for a final variable declaration.
9 final List<int>? list = [1, 2];
10 final Map<String, int>? m = {'a': 1};
Unnecessary nullable type for a final variable declaration.
10 final Map<String, int>? m = {'a': 1};
11 final bool? flag = true;

Valid

example.dartdart
final int a = 3;
final int? nullable = maybeNull();
var x = 5;
int? topLevel = 3;

class C {
  final int? field = 3;
  int? notFinal;

  void method() {
    final int? fromCall = compute();
    final int? explicit = null;
    int? mutable = 3;
    print('$fromCall $explicit $mutable');
  }
}

int? maybeNull() => null;
int? compute() => null;

How to configure

Set the severity of unnecessary-nullable-for-final-variable-declarations in your falcon.json:

falcon.jsonjson
{
  "linter": {
    "rules": {
      "style": {
        "unnecessary-nullable-for-final-variable-declarations": "error"
      }
    }
  }
}