Bad state: No element

Bad state: No element

Quick Answer

You called .first, .last, or .single on an empty iterable.

Why This Happens

In Dart, calling .first, .last, or .single on an empty List or Iterable throws a StateError because there is no element to return. Use .firstOrNull, .isEmpty checks, or firstWhere with an orElse callback to handle the empty case.

The Problem

final list = <String>[];
final item = list.first; // List is empty!

The Fix

final list = <String>[];
final item = list.firstOrNull ?? 'default';

Step-by-Step Fix

  1. 1

    Identify the error

    Look at the error message: Bad state: No element. This means .first, .last, or .single was called on an empty collection.

  2. 2

    Find the cause

    Check the stack trace to find which collection was empty, and determine why it had no elements at that point.

  3. 3

    Apply the fix

    Use .firstOrNull, check .isEmpty before accessing, or use .firstWhere with an orElse fallback.

Bugsly catches this automatically

Bugsly's AI analyzes this error pattern in real-time, explains what went wrong in plain English, and suggests the exact fix — before your users even report it.

Try Bugsly free