Skip to content

nullable_to_string

Reports a value that may be null made into text, which then reads “null”. Give a fallback, or check for null first.

Tier
advisory
Scope
Dart
Lowest preset
strict
Fix
none

A value that may be null made into text:

  • an interpolation of it: 'Hello, $name';
  • a call of toString() on it with .: count.toString().

Where the value is null, the text reads “null”, in a label, a path or a message to the user. The violation covers the value or the call.

It is silent where “null” is the right text:

  • in an argument of a call that writes to a log: print, debugPrint, a function or method named log, a method of a value whose class is named Logger or ends so, and a call that logging_calls names;
  • in an assert, a throw, an argument of an exception’s or error’s constructor, the members of an exception or error class, and a toString.

It does not report either:

  • a call with ?.;
  • a value of type Object? or dynamic;
  • a value that stringified_async_value or default_to_string reports;
  • a value guarded by a null test before it that does not promote it: a public field in price != null ? '$price' : '';
  • a group of a regular-expression match;
  • a value whose type is a type parameter that may be nullable.

A missing value shows up as the word “null” on the screen or in a URL, where a placeholder or a check was meant.

The rule is in strict only because a code base with much text of optional values gets many reports that are intended.

Violating
Text('Hello, ${user.nickname}')
Corrected
Text('Hello, ${user.nickname ?? user.name}')

Set under the assay: key of the project’s root analysis_options.yaml.

Rule parameter Default Effect
logging_calls [] The names of further functions and methods that write their arguments to a log, such as the methods of your own logger. print, debugPrint, every function or method named log, and every method of a value whose class is named Logger or ends so, count without it.
enabled true false switches the rule off for the whole project.
exclude []; the presets give the test directories Path globs where the rule is silent. Your list replaces the presets’ list.

The presets set exclude to test/**, integration_test/** and test_driver/**: in a test, a value that may be null is made text to say what the test saw.

Write why on the line directly above the suppression:

// The report shows a missing value as null on purpose.
// ignore: nullable_to_string
final shown = '$first';

// ignore_for_file: assay/nullable_to_string silences it in a whole file, and the prefixed // ignore: assay/nullable_to_string works too. See Suppressions.