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

Flutter开发HTTP解析JSON遇List<Post>无'lenght'getter错误求助

问题根因

报错的核心原因是拼写错误:Dart 数组的长度属性为length,你在 ListView.separated 的 itemCount 参数中错写为lenght,多输入了一个字母e,导致运行时找不到对应属性抛出NoSuchMethodError。

修复方案

第一步:修正拼写错误

找到业务代码里的这一行:

itemCount: snapshot.data.lenght,

替换为正确拼写:

itemCount: snapshot.data.length,

修改后即可解决当前报错。

第二步:可选优化(避免后续空安全、类型报错)

为了代码更健壮,建议做如下调整:

  1. 给FutureBuilder指定泛型,明确数据类型:
// 修改FutureBuilder声明
FutureBuilder<List<Post>>(
  future: getData as Future<List<Post>>,
  builder: (BuildContext context, AsyncSnapshot<List<Post>> snapshot) {
  1. 加载完成后先判空,避免空指针异常:
    在ConnectionState.done分支内先做校验:
else if (snapshot.connectionState == ConnectionState.done) {
  // 新增判空逻辑
  if (snapshot.hasError || !snapshot.hasData || snapshot.data!.isEmpty) {
    return const Center(child: Text("暂无数据或加载失败"));
  }
  // 拿到解析好的数组直接使用
  final postList = snapshot.data!;
  return ListView.separated(
    itemBuilder: (context,index){
      return ListTile(
        leading: const Icon(Icons.local_post_office),
        title: Text(postList[index].title),
        subtitle: Text(postList[index].body),
      );
    },
    separatorBuilder: (context,index)=>const Divider(),
    itemCount: postList.length,
  );
}

内容的提问来源于stack exchange,提问作者Meriç Türkyılmaz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 10:45:03