Flutter:RangeError(索引):无效值:不在0..14范围内,包括:15
Posted
技术标签:
【中文标题】Flutter:RangeError(索引):无效值:不在0..14范围内,包括:15【英文标题】:Flutter: RangeError (index): Invalid value: Not in range 0..14, inclusive: 15 【发布时间】:2020-06-30 20:09:07 【问题描述】:我正在使用 bloc 设计模式和 (flutter_bloc
lib) 构建一个 ListView
,当只放置列表长度并返回小部件时,列表是分页的并且工作正常,
但是当我尝试在列表中添加一个指示器并为 itemCount 添加 + 1
以加载 UI 时,就会出现问题
错误
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
列表代码
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();
),
);
【问题讨论】:
【参考方案1】:首先检查长度。如果数组不会超出范围,则仅尝试使用 final Post post = state.posts[i];
访问该元素没试过,但我希望这对你有用。
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),));
```
【讨论】:
它就像一个魅力,非常感谢,但我不明白我的代码有什么问题以及你和我的区别 如果 i>=length,我的代码不会到达 state.posts[i] 这一行。但你的。如果它对您有用,请接受答案。 :) 完成,感谢您的澄清以上是关于Flutter:RangeError(索引):无效值:不在0..14范围内,包括:15的主要内容,如果未能解决你的问题,请参考以下文章
Flutter:DioError [DioErrorType.DEFAULT]:RangeError(索引):无效值:只有有效值为0:
RangeError(索引):无效值:不在 0..6 范围内,包括:-2
颤振错误:RangeError(索引):无效值:不在0..2范围内,包括:3
颤振:RangeError(索引):无效值:不在包含范围内0..27:28