Flutter Best Practices

Chapter 1 · Practice 2 of 5

Prefer flow analysis over the ! operator

From Dart and null safety

Why it matters

The ! operator casts a nullable value to its non-nullable type. The Dart docs are blunt about it: the ! operator always throws if the value is null. Each ! is a runtime crash you have chosen to risk instead of a compile-time check.

Dart's flow analysis can usually prove a value is non-null for you:

  • Copy a nullable field into a local variable, check it, then use the local.
  • Use ?? for a default, ?. for an optional call, or an if (x case final value?) pattern.
  • Return early when the value is missing.

Fields cannot be promoted the same way as locals in every case, which is why copying to a local is the common fix.

Do

  • Copy a nullable field to a local, check it, then use the local
  • Use ?? and ?. for defaults and optional calls

Avoid

  • Using ! to silence an analyzer error you do not understand

Example

Dart
// Risky: throws if user is null
Text(user!.name);

// Safe: flow analysis promotes the local
final current = user;
if (current == null) return const SignInPrompt();
return Text(current.name);