Beware: Flutter/Dart's Iterable.first throws Bad state: No element

04/24/2019

While working on a Flutter app I ran into an exception in a ListView.separated that took me entirely too long to find the root issue. While scrolling I suddenly encountered this error:

Bad state: No element

My first instinct was something was wrong with the widget’s state. After some searching I was tipped off to look in another area, Dart 2.2’s Iterable.first. I was surprised to find that first, Throws a StateError if this is empty. Otherwise returns the first element in the iteration order, equivalent to this.elementAt(0).

What I didn’t know is my data set was coming in over HTTPS and had changed to be an empty array. My once safe jobs.first.title became dangerous!

the-more-you-know

I used a null-aware operator (?.) along with a default value (??), and added the helper function to my model. Keeping my widget’s a bit cleaner. Now I’m safe if jobs is null or [] (empty).

String getFirstTitle() => jobs?.isNotEmpty ?? false ? jobs.first.title : 'Unknown';

I was bummed that Iterable.first throws an exception in Dart instead of just returning null, so I’m stuck just using helper functions. 🙁