You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter ListView.builder报RangeError索引越界,itemCount应如何设置?

问题原因

你遇到的索引越界报错是因为ListView.builder未配置itemCount属性时,会默认生成无限个列表项,当滚动到的下标超过接口返回的table数组的最大合法下标时,就会触发该错误。

修复方案

给ListView.builder添加itemCount属性,值为返回的table数组的长度即可,为了兼容空数据场景建议添加空安全兜底,修改后的代码如下:

Widget build(BuildContext context) {
    return Scaffold(
    appBar: AppBar(
        title: const Text(
          'Products',
         ),
       ),
    body: Center(
       child: FutureBuilder(
          future: fetchPhotos(),
               builder: (ctx, snapShot) {
                    if (snapShot.connectionState == ConnectionState.waiting) {
                         return const CircularProgressIndicator();
                     } else {
                        // 提前提取table数组,加空安全处理避免空异常
                        final tableList = snapShot.data?["table"] as List? ?? [];
                        return ListView.builder(
                          // 新增itemCount配置
                          itemCount: tableList.length,
                          itemBuilder: (context, index) {
                             final item = tableList[index];
                             return ListTile(
                              leading: const CircleAvatar(
                                 backgroundColor: Colors.red,
                              ),
                               title: Text(item["name"]),
                               subtitle: Text(
                                  "price: ${item["class_id"]}"),
                           );
                         },
                       );
                 }
               },
              ),
            ),
          );
         }

内容的提问来源于stack exchange,提问作者user16867349

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 11:30:01