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

Flutter调用API时控制台返回数据但报[]被调用在null对象上错误如何解决

问题根因
  • snapshot.hasData仅能校验snapshot.data非空,无法保证嵌套的data、Result字段非空,只要其中一层字段为null,后续链式调用属性就会抛出你遇到的空对象调用错误
  • 若Result字段为列表类型,你没有通过下标访问对应位置的元素,直接调用列表本身不存在的image_url、name属性,也会返回null触发报错
  • ListView.builder的itemCount写死为5,若实际返回的列表长度小于5,访问超出范围的元素也会触发空异常
修复步骤
  1. 先确认实体类的字段名和接口返回的字段名完全匹配,避免大小写拼写错误、字段名不对应导致的解析后字段为null的问题
  2. 提前对嵌套字段做非空校验,不要直接链式访问无保护的属性
  3. 若Result为列表类型,在itemBuilder中通过下标访问对应元素,itemCount取列表实际长度
  4. 所有可能为空的属性都添加空安全兼容,为空时设置默认占位值
修正后的代码示例
body: Container(
  height: MediaQuery.of(context).size.height,
  width: MediaQuery.of(context).size.width,
  child: StreamBuilder<ApiResponse<CategoryResponse>>(
    stream: categoryBloc.subject.stream,
    builder: (context, AsyncSnapshot<ApiResponse<CategoryResponse>> snapshot) {
      if (snapshot.hasData) {
        // 提前提取数据并做非空判断
        final categoryResult = snapshot.data?.data?.Result;
        // 处理Result为空/无数据的场景
        if (categoryResult == null) {
          return const Center(child: Text("暂无数据"));
        }
        // 如果Result是单个对象,直接渲染,不需要ListView
        if (categoryResult is! List) {
          return Card(
            child: Column(
              children: <Widget>[
                ListTile(
                  leading: CircleAvatar(
                    backgroundImage: NetworkImage(categoryResult.image_url ?? "你的占位图地址"),
                  ),
                  title: Text(categoryResult.name ?? "未命名分类"),
                ),
              ],
            ),
          );
        }
        // 如果Result是列表,动态渲染列表
        return ListView.builder(
          itemCount: categoryResult.length,
          itemBuilder: (BuildContext context, int index) {
            final currentCategory = categoryResult[index];
            return Card(
              child: Column(
                children: <Widget>[
                  ListTile(
                    leading: CircleAvatar(
                      backgroundImage: NetworkImage(currentCategory.image_url ?? "你的占位图地址"),
                    ),
                    title: Text(currentCategory.name ?? "未命名分类"),
                  ),
                ],
              ),
            );
          },
        );
      } else if (snapshot.hasError) {
        return Text("${snapshot.error}");
      }
      return const Center(child: ColorLoader());
    }
  )
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 06:36:04