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

Flutter中能否用where查询配合StreamBuilder过滤Firestore已审核餐厅?

可行,实现方法如下

你只需要在Firestore的集合查询中添加where条件,过滤出approved字段为true的餐厅文档,就能实现需求。

修改后的完整代码

CollectionReference restaurants = FirebaseFirestore.instance.collection("Restaurants");
child: StreamBuilder(
  stream: restaurants.where('approved', isEqualTo: true).snapshots(), // 添加where过滤条件
  builder: (context, AsyncSnapshot<QuerySnapshot> 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!.docs.isEmpty) {
      return const Center(child: Text('暂无已审核餐厅'));
    }

    return ListView(
      children: snapshot.data!.docs.map((restaurantDoc) {
        // 明确获取文档数据,避免变量名冲突
        Map<String, dynamic> data = restaurantDoc.data()! as Map<String, dynamic>;
        return Card(
          child: Container(
              padding: EdgeInsets.all(MediaQuery.of(context).size.height / 150),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Column(
                    children: [
                      Container(
                        width: MediaQuery.of(context).size.width / 1.06,
                        height: MediaQuery.of(context).size.height / 8,
                        decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(10),
                            color: Colors.white38,
                            image: DecorationImage(
                                fit: BoxFit.cover,
                                image: AssetImage(AppImages.foodImg))),
                      ),
                      SizedBox(height: MediaQuery.of(context).size.height / 200,),
                      Text(data['restaurantName'], style: const TextStyle(fontWeight: FontWeight.w700,fontSize: 12),),
                      Text(data['address'],style: const TextStyle(fontSize: 11),),
                      
                    ],
                  ),
                ],
              )
          ),
        );
      }).toList(),
    );
  },
),

关键说明

  • 确保Firestore中每个餐厅文档都包含approved字段,且类型为布尔值(true表示已审核),如果字段名或类型不同,需对应调整where条件的参数。
  • 原代码直接使用snapshot.data!存在空指针风险,新增的状态处理可以提升界面稳定性,覆盖加载中、出错、无数据等场景。
  • 将单个文档的变量名从restaurants改为restaurantDoc,避免和集合变量名冲突,提升代码可读性。

内容的提问来源于stack exchange,提问作者H. M. Zaheer Asghar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 07:40:27