首页 > 解决方案 > 颤振:RangeError(索引):无效值:不在包含范围内0..52:53即使有项目计数也会出错

问题描述

使用颤振以列表形状的结构显示一些内容。我正在按照这种模式从 JSON 文件中获取数据:

[
  {
    "id":1,
    "name": "foo",
    "description":"foo description",
    "effects": [
      "foo effect"
    ]
  },
  ...
  {
    "id":54,
    "name": "foo 54",
    "description":"foo description 54",
    "effects": [
      "foo effect 54"
    ]
  }
]

我正在使用 aListView.builder来显示内容:

  final List<String> itemsAssetnumber = [
    "01", "02", "03", "04", "05", "06", "07", "08", "09",
    "11", "12", "13", "14", "15", "16", "17", "18", "19",
     "22", "23", "24", "25", "26", "27", "28", "29", "33",
      "34", "35", "36", "37", "38", "39", "44", "45", "46",
       "47", "48", "49", "55", "57", "58", "59", "66", "67",
        "68", "69", "77", "78", "79", "88", "89", "99"];

      ListView.builder(
        itemCount: data.length, // length == 54
        itemBuilder: (context, index){
          return Card(
            child: ListTile(
              onTap: (){},
              title: Text(data[index]['name']),
              subtitle: Text(data[index]['description']),
              leading: CircleAvatar(
                backgroundImage: AssetImage('assets/items/${itemsAssetnumber[index]}.png')),
          ));
        },
      ),

但是当我滚动到列表末尾时,我不断收到此堆栈跟踪,请参见此处

════════ Exception caught by widgets library ═══════════════════════════════════
The following RangeError was thrown building:
RangeError (index): Invalid value: Not in inclusive range 0..52: 53

When the exception was thrown, this was the stack
#0      List.[] (dart:core-patch/growable_array.dart:166:60)
#1      ItemsScreen.build.<anonymous closure>
package:tft_app/screens/items_screen.dart:30
#2      SliverChildBuilderDelegate.build
package:flutter/…/widgets/sliver.dart:448
#3      SliverMultiBoxAdaptorElement._build.<anonymous closure>
package:flutter/…/widgets/sliver.dart:1136
#4      _HashMap.putIfAbsent (dart:collection-patch/collection_patch.dart:140:29)
...
════════════════════════════════════════════════════════════════════════════════

我错过了什么?

标签: flutterlistviewdart

解决方案


推荐阅读