Christian
Christian

Reputation: 26427

Which pattern should I use to throw specific errors when a variable is null in dart?

I currently use:

  int get displayFlex => displaySegment == null
      ? throw StateError("Note is not yet processed by the Widget")
      : displaySegment!.flex;

The fact that I need to use ! after displaySegment! makes me think that there might be a better way to write this code. Is there a better pattern?

Upvotes: 0

Views: 25

Answers (1)

lrn
lrn

Reputation: 71813

Not sure about "better", but:

int get displayFlex => 
  (displaySegment ?? throw StateError("Note is not yet processed by the Widget")).flex;

is valid.

I'd probably do the more elaborate and readable

int get displayFlex {
  var displaySegment = this.displaySegment;
  if (displaySegment == null) throw StateError("Note is not yet processed by the Widget");
  return displaySegment.flex;
}

Upvotes: 1

Related Questions