Flutter开发HTTP解析JSON遇List<Post>无'lenght'getter错误求助
问题根因
报错的核心原因是拼写错误:Dart 数组的长度属性为length,你在 ListView.separated 的 itemCount 参数中错写为lenght,多输入了一个字母e,导致运行时找不到对应属性抛出NoSuchMethodError。
修复方案
第一步:修正拼写错误
找到业务代码里的这一行:
itemCount: snapshot.data.lenght,
替换为正确拼写:
itemCount: snapshot.data.length,
修改后即可解决当前报错。
第二步:可选优化(避免后续空安全、类型报错)
为了代码更健壮,建议做如下调整:
- 给
FutureBuilder指定泛型,明确数据类型:
// 修改FutureBuilder声明 FutureBuilder<List<Post>>( future: getData as Future<List<Post>>, builder: (BuildContext context, AsyncSnapshot<List<Post>> snapshot) {
- 加载完成后先判空,避免空指针异常:
在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
相关产品推荐
相关产品推荐

