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

Flutter使用cloud_firestore读取数据时出现类型不匹配报错如何解决

问题原因

  • 首次Expected a value of type 'Map<String, dynamic>', but got one of type 'Null'报错:初始代码users.doc().get()没有传入uid参数,doc()空参调用会生成随机的新文档ID,请求的是不存在的空文档,data()自然返回null。
  • 第二次同类型报错:修改代码后你错误将snapshot.data(本身是_JsonDocumentSnapshot类型)直接强转成Map,正确操作是调用data()方法才能获取文档的字段映射。同时你取值时写的data['username']和存储的字段名userName大小写不一致,也会导致后续取值为空。
  • 第三次Bad state: cannot get a field报错:snapshot.data是DocumentSnapshot对象,不是JSON字符串,不能直接传入jsonDecode解析,属于方法调用错误。额外的RenderFlex溢出报错是因为错误文本过长,Column没有加滚动属性导致的。

解决方案

完整修复代码

// 提前判断用户登录状态,避免空异常
final String? uid = FirebaseAuth.instance.currentUser?.uid;
final CollectionReference users = FirebaseFirestore.instance.collection('users');

// uid为空时先返回登录提示
if (uid == null) {
  return const Text("请先登录");
}

return FutureBuilder<DocumentSnapshot>(
  future: users.doc(uid).get(),
  builder: (context, AsyncSnapshot<DocumentSnapshot> snapshot) {
    if (snapshot.connectionState != ConnectionState.done) {
      return const SizedBox(
        width: 50,
        child: LinearProgressIndicator(),
      );
    }

    if (snapshot.hasError) {
      // 加SingleChildScrollView避免长错误文本溢出
      return SingleChildScrollView(
        child: SelectableText(snapshot.error.toString()),
      );
    }

    // 额外判断文档是否真实存在,过滤空数据
    if (!snapshot.hasData || !snapshot.data!.exists) {
      return const Text('No data found');
    }

    // 正确调用data()方法获取字段映射,字段名和存储保持一致
    Map<String, dynamic> data = snapshot.data!.data() as Map<String, dynamic>;
    return Text("User Name: ${data['userName']}");
  },
);

补充排查点

如果修改后还是获取不到数据,检查Firestore安全规则是否开放了对应uid文档的读取权限,规则限制也会导致读取空数据或权限报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 17:48:00