hesham shawky
hesham shawky

Reputation: 1151

Flutter: RangeError (index): Invalid value: Not in range 0..14, inclusive: 15

I'm building a ListView using bloc design pattern and ( flutter_bloc lib ) the list is paginated and working fine when just put the list length and return widget,

But the issue happens when I try to add an indicator down the list and adding + 1 for itemCount for loading UI purpose

The error

Restarted application in 1,900ms.

[38;5;248m════════ Exception caught by widgets library ═══════════════════════════════════[39;49m
[38;5;244mThe following RangeError was thrown building:[39;49m
RangeError (index): Invalid value: Not in range 0..14, inclusive: 15

[38;5;244mWhen the exception was thrown, this was the stack[39;49m
[38;5;244m#0      List.[]  (dart:core-patch/growable_array.dart:149:60)[39;49m
[38;5;248m#1      _HomePageState.build.<anonymous closure>.<anonymous closure>[39;49m
[38;5;244m#2      SliverChildBuilderDelegate.build[39;49m
[38;5;244m#3      SliverMultiBoxAdaptorElement._build.<anonymous closure>[39;49m
[38;5;244m#4      _HashMap.putIfAbsent  (dart:collection-patch/collection_patch.dart:139:29)[39;49m
[38;5;244m...[39;49m
[38;5;248m════════════════════════════════════════════════════════════════════════════════[39;49m

The code for the list

return BlocListener<PostsBloc, PostsState>(
  listener: (context, state) {
    if ( state is PostsError ) {
      Scaffold.of(context).showSnackBar(
        SnackBar(content: Text(state.errMsg))
      );
    }
  },        
  child: BlocBuilder<PostsBloc, PostsState>(builder: (context, state) {
    if (state is PostsInitial || state is PostsLoading) {
      return loading();
    } else if (state is PostsLoaded) {
      return ListView.builder(
        itemCount: state.hasReachedMax
            ? state.posts.length
            : state.posts.length + 1,
        controller: _scrollController,
        itemBuilder: (BuildContext context, int i) {
          final Post post = state.posts[i];

          return (i >= state.posts.length) 
          ? Center(child: CircularProgressIndicator())
          : ListTile(leading: Text(i.toString()), title: Text(post.title, style: TextStyle(fontWeight: FontWeight.bold),));
        }
      );
    }

    return errorMsg();
  }),
);

Upvotes: 1

Views: 1299

Answers (1)

Suman Maharjan
Suman Maharjan

Reputation: 1122

First check the length. If the array wont go out of bound, then only try to access the element using final Post post = state.posts[i];

Haven't tried but i hope this will work for you.

itemBuilder: (BuildContext context, int i) {
          if(i >= state.posts.length){
            return Center(child: CircularProgressIndicator());
          }
          final Post post = state.posts[i];
          ListTile(leading: Text(i.toString()), title: Text(post.title, style: TextStyle(fontWeight: FontWeight.bold),));
        }
```

Upvotes: 3

Related Questions