0

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?

Christian
  • 25,249
  • 40
  • 134
  • 225
  • The reason why you need to use `!` is because [non-local variables won't get type promoted](https://stackoverflow.com/q/65035574/). – jamesdlin Apr 10 '21 at 20:08

1 Answers1

1

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;
}
lrn
  • 64,680
  • 7
  • 105
  • 121