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

Flutter解析JSON时无法获取全部username与email字段记录怎么办

问题原因
  • 核心错误是ListView.builder的itemCount参数配置和你的渲染逻辑不匹配:你设定了奇数位置返回Divider分割线、偶数位置渲染数据项,相当于每条数据要占用2个列表位置,但你现在把itemCount设为_quakes.length(数据源本身的长度),导致列表渲染的总位置数不够,只能拿到前一半的数据。
  • 对应你遇到的仅返回5条数据的现象,可以反推你的_quakes数组实际有10条有效数据:当前itemCount设为10时,position最大值为9,计算得到的最大数据索引为9 ~/ 2 = 4,刚好只能取到前5条数据。
修复方案

方案1:调整原逻辑的itemCount取值

将itemCount改为2 * _quakes.length - 1(减去1是因为最后一条数据后不需要额外加分割线)即可,完整代码如下:

body: new Center(
  child: new ListView.builder(
    // 仅修改这一行的itemCount取值
    itemCount: 2 * _quakes.length - 1,
    padding: const EdgeInsets.all(16.8),
    itemBuilder: (BuildContext context , int position)
    {
      if(position.isOdd ) return new Divider();
      int index = position ~/ 2;
      return new ListTile(
        title: new Text("${_quakes[index]['username']}"
        , style: new TextStyle(fontSize: 19.2),),
        subtitle: new Text("${_quakes[index]['email']}",
        style: new TextStyle(fontSize: 14.9),),
      );
    }
  )
)

方案2(可选优化):使用ListView.separated简化逻辑

Flutter提供了自带分隔线配置的ListView.separated组件,不需要手动判断位置奇偶,逻辑更简洁不易出错,代码如下:

body: new Center(
  child: new ListView.separated(
    itemCount: _quakes.length,
    padding: const EdgeInsets.all(16.8),
    // 直接配置分隔线
    separatorBuilder: (BuildContext context, int index) => new Divider(),
    itemBuilder: (BuildContext context , int index)
    {
      return new ListTile(
        title: new Text("${_quakes[index]['username']}"
        , style: new TextStyle(fontSize: 19.2),),
        subtitle: new Text("${_quakes[index]['email']}",
        style: new TextStyle(fontSize: 14.9),),
      );
    }
  )
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 22:54:00