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

Flutter Firestore按字段查询出现类型匹配错误,请求协助解决

问题解决:Firestore 查询类型不匹配错误

错误原因

你用where()构建的是Query对象,调用get()后返回的是Future<QuerySnapshot>(包含多个匹配文档的结果集合),但你的FutureBuilder明确指定了泛型为DocumentSnapshot,两者类型不兼容,因此抛出类型赋值错误。

修复方案

既然是按唯一字段查询,只需从查询结果的文档列表中取出第一个文档即可。修改后的完整代码如下:

class ItemDetails extends StatelessWidget {
  Map routeData = {};

  @override
  Widget build(BuildContext context) {
    routeData = ModalRoute
        .of(context)
        ?.settings
        .arguments as Map;
    print(routeData);

    final Query docRef = FirebaseFirestore.instance.collection("table_name")
        .where("id",isEqualTo: "gze1thwyhreqpbspu611aa3ejmhemxkthphyq3kugp5vqm75fwv");

    // 修改FutureBuilder泛型为QuerySnapshot,匹配Query.get()的返回类型
    return FutureBuilder<QuerySnapshot>(
      future: docRef.get(),
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return Scaffold(
            appBar: AppBar(
              title: Text("Waiting for future..."),
            ),
            body: Center(child: CircularProgressIndicator()),
          );
        } else if (snapshot.hasError) {
          return Scaffold(
            appBar: AppBar(
              title: Text("Error"),
            ),
            body: Center(child: Text("Error: ${snapshot.error}")),
          );
        } else if (snapshot.data?.docs.isEmpty ?? true) {
          // 处理无匹配文档的情况
          return Scaffold(
            appBar: AppBar(
              title: Text("Not Found"),
            ),
            body: Center(child: Text("No matching document found")),
          );
        } else {
          // 取出第一个匹配的文档
          final DocumentSnapshot docSnapshot = snapshot.data!.docs.first;
          final data = docSnapshot.data() as Map<String, dynamic>;

          print(data);
          return Scaffold(
              appBar: AppBar(
                title: Text(data?["name"] ?? "Item Details"),
              ),
              body: SingleChildScrollView(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children:  [
                      Text("Region: " + (data?["reg"] ?? "")),
                      Text("Country: " + (data?["country"] ?? "")),
                      Text("Type: " + (data?["type"] ?? "")),
                      Text("Last updated (red text): " + DateFormat('d MMMM y')
                          .format(DateTime.fromMillisecondsSinceEpoch(data?['dlastupd'] * 1000 ?? 0))),
                    ],
                  )
              )
          );
        }
      },
    );
  }
}

关键修改点

  1. 调整FutureBuilder泛型为QuerySnapshot,与Query.get()的返回类型对齐
  2. 通过snapshot.data!.docs.first获取查询结果中的第一个文档
  3. 添加无匹配文档的判断逻辑,避免空指针异常
  4. 对可能为空的字段增加空值处理(??操作符),提升代码健壮性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 22:45:21