Flutter RangeError (index): Invalid value: Valid value range is empty: 0
RangeError (index): Invalid value: Valid value range is empty: 0Short answer
You read an index from a list that has no elements. A list index must be at least 0 and less than the list's length, so any index on an empty list fails. In Flutter the list is usually still empty because data has not loaded, or itemCount does not match the list. Guard the read and build only after the data arrives.
Fix it fast
1Find out which cause you have
The stack trace names the line in your code that reads the list. Print the list length just before it.
debugPrint('items: ${items.length}');2Match what you see, then jump to its fix
- 1
The error shows on first paint and disappears after data loads, or stays when the request failsThe list is empty while the screen is already builtFix - 2
Valid value range is 0..n for a list with n+1 items, and the index equals the lengthThe index is past the last valid positionFix - 3
The trace passes through itemBuilder and the error appears while scrollingListView.builder asks for more rows than the list holdsFix
- 1
What does the error look like?
RangeError (index): Invalid value: Valid value range is empty: 0RangeError thrown from a list index read on an empty list
Cause 1 of 3
The list is empty while the screen is already built
1Check
A FutureBuilder builds once with null data before the future completes, so code that reads snapshot.data![0] fails on that first frame.
debugPrint('state: ${snapshot.connectionState}, data: ${snapshot.data}');2Fix
Show a loader until the data exists and handle the empty result as its own case.
FutureBuilder<List<Item>>(
future: _future, // created in initState, not in build
builder: (context, snapshot) {
if (snapshot.connectionState != ConnectionState.done) {
return const CircularProgressIndicator();
}
final items = snapshot.data ?? const <Item>[];
if (items.isEmpty) return const Text('No items yet');
return Text(items.first.title);
},
)3Verify
The first frame shows the loader and no RangeError appears in the console.
flutter runConfirmed by api.flutter.dev
Cause 2 of 3
The index is past the last valid position
1Check
The docs define a valid index as non-negative and less than the length, so the last item sits at length minus one.
debugPrint('index: $i, length: ${items.length}');2Fix
Loop with i < items.length, and read the last element with items[items.length - 1] only after checking the list is not empty.
for (var i = 0; i < items.length; i++) {
use(items[i]);
}
if (items.isNotEmpty) use(items[items.length - 1]);3Verify
Run the screen with zero, one and many items; none throws.
flutter testConfirmed by api.dart.dev
Cause 3 of 3
ListView.builder asks for more rows than the list holds
1Check
itemBuilder is called for indexes from zero up to, but not including, itemCount. If itemCount comes from another list or a fixed number, it can be larger than the list you index.
grep -n "itemCount" lib/ -r2Fix
Take itemCount from the same list that itemBuilder reads.
ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) => Text(items[index].title),
)3Verify
Scroll to the end of the list and refresh it with fewer items.
flutter runConfirmed by api.flutter.dev
How do I stop it coming back?
- Treat empty as a normal state and design a screen for it.
- Create futures in initState, never inside build.
- Always derive itemCount from the list you index.
- Use isEmpty or isNotEmpty before first, last or a fixed index.
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.
Which stack is behind this page?
Projects of mine built on the same technologies:
- TaxiDexMy own multi-tenant taxi dispatch SaaS: API, dispatcher portal, driver and passenger apps, and the servers underneath.
- Qist BazaarA buy-now-pay-later marketplace built from a blank repo, now past 100K downloads on Google Play.
- SessionBirdAn omnichannel engagement suite in Flutter: campaigns, chatbot, tickets, analytics and live calling.
Related fixes
Mobile apps
AudioCache has no play method after updating audioplayers
The method 'play' isn't defined for the type 'AudioCache'.
Since audioplayers 1.0, AudioCache only turns asset files into local files and caches them.
2 causes, each with a fixMobile apps
Flutter Bloc throws that emit was called after the event handler completed
emit was called after an event handler completed normally.
Each on<Event> handler gets its own Emitter, and it stops working the moment the handler's returned Future completes.
2 causes, each with a fixMobile apps
analysis_options.yaml: the URI it includes can't be found
include_file_not_found
The analyzer reports include_file_not_found when the file named after include: in analysis_options.yaml does not resolve.
2 causes, each with a fixMobile apps
Dart error: the body might complete normally and return null for a non-nullable type
body_might_complete_normally
Dart found a path through your function or callback that reaches the closing brace without a return.
3 causes, each with a fixMobile apps
Dart throws ConcurrentModificationError while looping over a list
ConcurrentModificationError
Dart throws this when a collection changes size while something iterates it.
2 causes, each with a fixMobile apps
Dart cannot turn a compact timestamp like 20201101153000 into a DateTime
FormatException: Invalid date format
DateTime.parse accepts a subset of ISO 8601, and a time part must be introduced by T or a space.
2 causes, each with a fix