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

Flutter Firebase问题:Drawer展示全部Firestore用户,需仅显示当前登录用户数据

问题修复方案

问题根因

  • 你的StreamBuilder当前监听的是users集合下的全部文档快照,因此会遍历返回所有用户的信息
  • 已在getUser方法中获取到的当前登录用户uid,没有被用于数据查询过滤

修复后的完整代码

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import '../screens/user_product_list_view.dart';

class UserDrawer extends StatefulWidget {
  UserDrawer({Key? key}) : super(key: key);

  @override
  _UserDrawerState createState() => _UserDrawerState();
}

class _UserDrawerState extends State<UserDrawer> {
  // 保存当前登录用户实例
  final User? currentUser = FirebaseAuth.instance.currentUser;

  @override
  void initState() {
    super.initState();
    // 保留调试日志,不需要可删除
    if (currentUser != null) {
      debugPrint("当前登录用户邮箱:${currentUser!.email}");
    }
  }

  // 登出方法
  Future<void> _signOut() async {
    try {
      await FirebaseAuth.instance.signOut();
      // 登出后跳转登录页,可根据自身路由逻辑修改
      if (mounted) {
        Navigator.pushReplacementNamed(context, '/login');
      }
    } catch (e) {
      debugPrint("登出失败:$e");
    }
  }

  @override
  Widget build(BuildContext context) {
    // 未登录状态直接返回提示
    if (currentUser == null) {
      return Drawer(
        child: Center(child: Text("请先登录")),
      );
    }
    return Drawer(
      child: SafeArea(
        child: Scaffold(
          backgroundColor: Theme.of(context).primaryColor,
          body: Column(
            children: [
              // 个人信息区域,仅监听当前用户单条文档
              StreamBuilder<DocumentSnapshot<Map<String, dynamic>>>(
                stream: FirebaseFirestore.instance
                    .collection('users')
                    .doc(currentUser!.uid)
                    .snapshots(),
                builder: (context, snapshot) {
                  if (snapshot.hasError) {
                    return const Text("加载用户信息失败");
                  }
                  if (!snapshot.hasData) {
                    return const CircularProgressIndicator();
                  }
                  // 拿到当前用户数据
                  Map<String, dynamic> userData = snapshot.data!.data()!;
                  return Stack(
                    children: [
                      Container(
                        padding: const EdgeInsets.only(top: 105),
                        height: 300,
                        width: double.infinity,
                        decoration: BoxDecoration(
                            color: Theme.of(context).primaryColorDark,
                            borderRadius: const BorderRadius.only(
                                bottomLeft: Radius.circular(120))),
                        child: Column(
                          children: [
                            // 头像可自行替换为userData中存储的头像链接渲染
                            CircleAvatar(
                              radius: 40,
                              backgroundColor: Colors.blueAccent,
                              child: Text(
                                userData['name']?.substring(0,1).toUpperCase() ?? '',
                                style: const TextStyle(fontSize: 28, color: Colors.white),
                              ),
                            ),
                            const SizedBox(height: 16),
                            Text(
                              userData['name'] ?? '未设置姓名',
                              style: const TextStyle(
                                  fontWeight: FontWeight.bold, fontSize: 20, color: Colors.white),
                            ),
                            const SizedBox(height: 8),
                            Text(
                              userData['email'] ?? currentUser!.email ?? '',
                              style: const TextStyle(fontSize: 16, color: Colors.white70),
                            ),
                          ],
                        ),
                      ),
                      Container(
                        padding: const EdgeInsets.symmetric(
                            horizontal: 20, vertical: 10),
                        height: 100,
                        width: double.infinity,
                        child: const Text(
                          '个人中心',
                          style: TextStyle(
                            fontSize: 24,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        decoration: BoxDecoration(
                            color: Theme.of(context).primaryColorLight,
                            borderRadius: const BorderRadius.only(
                                bottomLeft: Radius.circular(80))),
                      ),
                    ],
                  );
                },
              ),
              // 功能菜单区域
              Expanded(
                child: ListView(
                  padding: EdgeInsets.zero,
                  children: [
                    ListTile(
                      leading: const Icon(Icons.shopping_bag, color: Colors.white),
                      title: const Text("我的商品", style: TextStyle(color: Colors.white)),
                      onTap: () {
                        Navigator.push(context, MaterialPageRoute(builder: (_) => const UserProductListView()));
                      },
                    ),
                    const Divider(color: Colors.white24),
                    ListTile(
                      leading: const Icon(Icons.logout, color: Colors.white),
                      title: const Text("退出登录", style: TextStyle(color: Colors.white)),
                      onTap: _signOut,
                    ),
                  ],
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}

修改说明

  1. 直接监听当前登录用户uid对应的单条users文档,避免返回所有用户数据,切换登录账号时会自动监听对应用户的文档
  2. 补充了登出功能实现,点击后会清空Firebase登录状态,可根据自己的路由规则修改登出后的跳转逻辑
  3. 增加了未登录状态的兼容处理,避免空指针报错
  4. 可自行替换头像展示逻辑,直接读取userData['avatar']里存储的头像链接渲染即可

内容的提问来源于stack exchange,提问作者Md. Fazle Rabbi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 08:06:03