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

Dart/Flutter如何基于REST接口对象属性值过滤展示Snapshot数据

解决方案

首先先修正你的Posts模型定义,确保属性已提前声明:

class Posts {
  // 对应你构造方法中赋值的posts字段,类型和JSON返回值保持一致为字符串
  final String posts;
  Posts(Map<String, dynamic> json) : posts = json["number"];
}

完整可运行的业务代码如下

Widget _buildGridView() => StreamBuilder<List<Posts>?>(
  builder: (context, snapshot) {
    // 处理加载中状态
    if (snapshot.connectionState == ConnectionState.waiting) {
      return const Center(child: CircularProgressIndicator());
    }
    // 处理加载错误状态
    if (snapshot.hasError) {
      return Center(child: Text('加载出错:${snapshot.error}'));
    }
    // 处理无数据状态
    if (!snapshot.hasData || snapshot.data!.isEmpty) {
      return const Center(child: Text('暂无相关帖子'));
    }
    // 过滤出posts值为"1"的帖子,注意JSON返回的是字符串类型,不要用数字1判断
    final filteredList = snapshot.data!.where((item) => item.posts == "1").toList();
    return GridView.count(
      // 你原代码遗漏了crossAxisCount必填参数,根据需求修改每行展示数量即可
      crossAxisCount: 2,
      children: List.generate(filteredList.length, (index) {
        return _buildPlacesCell(filteredList[index]);
      })
    );
  }
);

之前报错的原因说明

  • The getter 'posts' isn't defined for the type 'List<Post>':snapshot.data是帖子列表集合,不是单个帖子对象,不能直接取posts属性,需要先遍历列表做过滤
  • The operator '[]' isn't defined for the type 'Post':自定义的Posts类没有重载[]运算符,不能用post["number"]的方式取值,直接调用类中声明的属性名即可
  • The body might complete normally, causing 'null' to be returned:StreamBuilder的builder方法要求所有逻辑分支都必须返回Widget,你之前的代码只在data不为空时返回了GridView,其余状态没有返回值,补全对应状态的返回即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 01:45:01