颤振错误:RangeError(索引):无效值:不在0..2范围内,包括:3

新手上路,请多包涵

我在 Flutter 中使用了很长的列表。所有项目都呈现正常,但我也收到以下错误:

 RangeError (index): Invalid value: Not in range 0..2, inclusive: 3

以下是我的代码:

 @override
Widget build(BuildContext context) {
return Container(
  child: getList(),
 );
}

以下是我的 getList() 方法:

 Widget getList (){
List<String> list = getListItems();
ListView myList = new ListView.builder(itemBuilder: (context, index){
  return new ListTile(
    title: new Text(list[index]),
  );
});
return myList;
}

以下是我的 getListItem() 方法:

 List<String> getListItems(){
return ["Faizan", "Usman", "Naouman"];
}

以下是错误截图:

在此处输入图像描述

原文由 Muhammad Faizan 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 953
2 个回答

您应该将 itemCount 参数传递给 ListView.builder 以使其知道项目数

Widget getList() {
  List<String> list = getListItems();
  ListView myList = new ListView.builder(
    itemCount: list.length,
    itemBuilder: (context, index) {
    return new ListTile(
      title: new Text(list[index]),
    );
  });
  return myList;
}

原文由 muttonlamb 发布,翻译遵循 CC BY-SA 4.0 许可协议

Listview.Builder 包含 itemcount 属性。你可以试试这个:

 Listview.Builder(
    itemCount : list.length,
    itemBuilde:(context, index)=>
);

原文由 ysakh 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题