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

Flutter Firebase实现:重复发送请求时显示已提交提示

问题分析与修复方案

现有代码的核心问题

  • 连接状态判断错误:snapshots()是实时数据流,ConnectionState.done仅在单次读取完成时触发,无法适配实时监听场景
  • 列表构建逻辑无效:ListView.builder的itemBuilder中返回null,导致无法渲染文本;且遍历所有请求会重复输出内容,逻辑冗余
  • 查询效率低下:拉取所有请求文档后再判断当前用户,没必要,可直接精准查询当前用户的请求记录

修复后的代码实现

final uid = FirebaseAuth.instance.currentUser!.uid;

StreamBuilder<QuerySnapshot>(
  stream: FirebaseFirestore.instance
      .collection("ADS")
      .doc(widget.selectedAds?['Uid'] ?? "")
      .collection("REQUESTS")
      // 精准查询当前用户的请求,减少数据读取量
      .where("UID", isEqualTo: uid)
      .snapshots(),
  builder: (context, snapshot) {
    // 处理加载状态
    if (snapshot.connectionState == ConnectionState.waiting) {
      return const CircularProgressIndicator(color: Colors.white);
    }

    // 判断当前用户是否已发送过请求
    bool hasSentRequest = snapshot.hasData && snapshot.data!.docs.isNotEmpty;

    return Text(
      hasSentRequest ? "请求已发送" : "发送请求",
      style: const TextStyle(color: Colors.white),
    );
  },
)

额外优化建议

  • 优化文档存储结构:将REQUESTS集合的文档ID直接设为请求用户的UID,这样可通过doc(uid)直接查询,进一步提升查询效率
  • 添加交互逻辑:将文本替换为InkWell或ElevatedButton,实现点击发送请求的功能,同时在发送时做重复请求校验,避免重复创建文档

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 15:52:35