Flutter Best Practices

Chapter 1 · Practice 1 of 5

Model "might be missing" in the type, not in comments

From Dart and null safety

Why it matters

Dart has sound null safety. The Dart docs define it this way: if an expression has a static type that does not permit null, then no possible execution of that expression can ever evaluate to null. That is a strong promise, but only if your types say what you mean.

  • Make a field nullable (String?) only when "no value" is a real state in your app, such as a user who has not set a bio yet.
  • Make everything else non-nullable and give it a value in the constructor.
  • When a value can be missing for several different reasons, consider a small sealed class instead of null, so each case is named.

The payoff is that the analyzer forces you to handle the missing case exactly where it can happen, and nowhere else.

Do

  • Use non-nullable types by default and add ? only for real "no value" states
  • Handle the null case once, at the edge where data enters your app

Avoid

  • Making fields nullable just to avoid writing a constructor parameter

Example

Dart
class Profile {
  const Profile({required this.name, this.bio});

  final String name; // always present
  final String? bio; // a real "not set yet" state
}

String bioLine(Profile p) => p.bio ?? 'No bio yet';