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

Flutter中从Cloud Firestore读取并实时展示Double值

Flutter实时读取并展示Cloud Firestore中的Double值

核心实现:用StreamBuilder监听文档变化

要实时获取Firestore数据的更新,直接用StreamBuilder组件绑定文档的快照流即可,它会自动处理数据加载、更新和UI刷新。

完整代码示例

假设你已经初始化了Firestore实例_firestore,且已获取到当前登录用户的邮箱loggedInUser?.email,将以下代码嵌入你的UI结构中:

StreamBuilder<DocumentSnapshot>(
  // 监听目标文档的实时快照流
  stream: _firestore.collection('guthaben').doc(loggedInUser?.email).snapshots(),
  builder: (context, snapshot) {
    // 处理加载状态
    if (snapshot.connectionState == ConnectionState.waiting) {
      return const Text('加载中...');
    }
    // 处理错误情况
    if (snapshot.hasError) {
      return const Text('数据加载失败');
    }
    // 文档不存在时的提示
    if (!snapshot.hasData || !snapshot.data!.exists) {
      return const Text('暂无金额数据');
    }
    // 读取double类型的geld字段
    double currentGeld = snapshot.data!['geld'] as double;
    // 在Text组件中展示数值
    return Text(
      '当前金额: $currentGeld',
      style: const TextStyle(fontSize: 18),
    );
  },
)

优化你的写入逻辑

你当前的set方法会直接覆盖整个文档,如果是要在原有金额基础上更新(比如累加),建议改用update结合FieldValue.increment,实现原子性更新,避免多端操作导致的数据不一致:

// 示例:累加指定金额(addAmount为double类型)
_firestore.collection('guthaben').doc(loggedInUser?.email).update({
  'geld': FieldValue.increment(addAmount),
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 14:25:35