Skip to main content

cast_nullable_to_non_nullable

Details about the 'cast_nullable_to_non_nullable' diagnostic produced by the Dart analyzer.

Don't cast a nullable value to a non-nullable type.

Description

#

The analyzer produces this diagnostic when an expression whose static type is nullable is cast to a non-nullable type. Casts of expressions whose static type is dynamic aren't reported.

A cast like this throws an exception at run time when the value is null, so it hides a null check that is easy to overlook.

Examples

#

The following code produces this diagnostic because the parameter o has the nullable type Object?, but is cast to the non-nullable type String:

dart
String f(Object? o) => o as String;

The following code produces this diagnostic because the parameter s has the nullable type String?, but is cast to the non-nullable type String:

dart
String f(String? s) => s as String;

Common fixes

#

If the value is never expected to be null, and the cast also changes the type, then use the not-null assertion operator (!) before the cast to make the null check explicit:

dart
String f(Object? o) => o! as String;

If the value is never expected to be null, and the type being cast to is the non-nullable version of the expression's static type, then replace the cast with the not-null assertion operator (!):

dart
String f(String? s) => s!;

If the value can be null, then cast to a nullable type instead:

dart
String? f(Object? o) => o as String?;