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

Firestore报错:期望Map<String,dynamic>类型却获取到Null的问题

问题

此前功能完全正常,现在出现报错:期望类型为Map<String, dynamic>,但实际获取到的是Null类型。当前请求仅返回文档Key,未返回对应的数据值,已多次检查用户ID。

相关Flutter代码:

class _DetailPageState extends State<DetailPage> {
  final db = FirebaseFirestore.instance;
  List<ChoicesModel> options = [];
  String id = "";

  @override
  void initState() {
    setState(() {
      id = Get.parameters["id"] ?? "";
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text(id),),
      body: id.isNotEmpty ? StreamBuilder<DocumentSnapshot>(
        stream: db.collection(collectionQrCode).doc(id).snapshots(),
        builder: (context, snapshot) {
          if (snapshot.hasError) {
            return const Center(child: Text("Some think is wrong"));
          } else if (snapshot.hasData) {
            
            Map<String, dynamic> data = snapshot.data!.data() as Map<String, dynamic>;
            print(data);
            return SizedBox(
              width: Get.width,
              child: Text("Noo"),
            );
          } else {
            return const Center(child: CircularProgressIndicator());
          }
        },
      ) : const Text("No Key"),
    );
  }
}

报错截图:
报错截图


解决办法
  1. 先判断文档是否存在
    StreamBuilder的snapshot.hasData仅代表Firestore返回了响应,但不对应ID的文档一定存在。必须添加文档存在性检查:
else if (snapshot.hasData) {
  // 新增:判断文档是否存在
  if (!snapshot.data!.exists) {
    return const Center(child: Text("该ID对应的文档不存在"));
  }
  Map<String, dynamic> data = snapshot.data!.data() as Map<String, dynamic>;
  print(data);
  return SizedBox(
    width: Get.width,
    child: Text("Noo"),
  );
}
  1. 检查Firestore权限规则
    若确认文档存在但无法读取,大概率是权限规则被修改。前往Firestore控制台查看权限设置,确保当前用户有权限读取collectionQrCode集合下的文档。

  2. 验证文档内容
    即使文档存在,若内部无任何字段,data()方法也会返回Null。去Firestore控制台查询对应ID的文档,确认是否包含有效数据。

  3. 安全处理类型转换
    避免强制类型转换引发崩溃,改用可空类型安全处理:

// 用可空类型接收,再判断数据是否为空
Map<String, dynamic>? data = snapshot.data?.data() as Map<String, dynamic>?;
if (data == null) {
  return const Center(child: Text("无可用文档数据"));
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 19:44:55