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

Flutter中如何从Cloud Firestore获取当前登录用户的uname字段

解决Firestore获取用户uname字段的问题

一、先修正注册时的Firestore存储逻辑(关键)

你当前用add()生成随机文档ID,无法直接和当前登录用户绑定,建议改成用FirebaseAuth返回的用户UID作为文档ID,这样后续能精准定位用户文档:

onPressed: () async {
  try {
    final newUserCredential = await FirebaseAuth.instance
        .createUserWithEmailAndPassword(
          email: email ?? 'error',
          password: password ?? 'error',
        );
    // 获取当前注册用户的UID
    final userId = newUserCredential.user?.uid;
    if (userId != null) {
      // 用UID作为文档ID,将用户信息存入Firestore
      await FirebaseFirestore.instance
          .collection('Users')
          .doc(userId)
          .set({'uname': username});
      
      Navigator.push(
        context,
        MaterialPageRoute(builder: (context) => home()),
      );
    }
  } catch (e) {
    print(e);
  }
}

二、在StatefulWidget(比如个人资料页)获取uname字段

在个人资料页面的State类中,通过用户UID直接查询对应文档:

1. 定义状态变量存储用户名

class ProfilePageState extends State<ProfilePage> {
  String? _userName;
  bool _isLoading = true;

  @override
  void initState() {
    super.initState();
    // 页面初始化时触发获取用户信息
    _fetchUserName();
  }

2. 实现获取用户名的方法

Future<void> _fetchUserName() async {
    // 获取当前登录用户
    final currentUser = FirebaseAuth.instance.currentUser;
    if (currentUser == null) {
      // 用户未登录,可添加跳转登录页等逻辑
      setState(() {
        _isLoading = false;
      });
      return;
    }

    try {
      // 通过UID查询Users集合中的对应文档
      final docSnapshot = await FirebaseFirestore.instance
          .collection('Users')
          .doc(currentUser.uid)
          .get();
      
      if (docSnapshot.exists) {
        // 从文档中取出uname字段
        setState(() {
          _userName = docSnapshot.data()?['uname'];
          _isLoading = false;
        });
      } else {
        setState(() {
          _userName = '未设置用户名';
          _isLoading = false;
        });
      }
    } catch (e) {
      print('获取用户名失败: $e');
      setState(() {
        _userName = '获取失败';
        _isLoading = false;
      });
    }
  }

3. 在build方法中展示数据

@override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('个人资料')),
      body: Center(
        child: _isLoading
            ? const CircularProgressIndicator()
            : Text('用户名: ${_userName ?? '未知'}'),
      ),
    );
  }
}

三、如果不想修改注册逻辑的替代方案(不推荐)

如果已经用add()生成了大量随机ID的文档,只能通过查询用户标识(比如邮箱)匹配,但需要注册时同时存储email字段:

Future<void> _fetchUserNameByEmail() async {
  final currentUser = FirebaseAuth.instance.currentUser;
  if (currentUser == null) return;

  try {
    // 通过邮箱查询Users集合
    final querySnapshot = await FirebaseFirestore.instance
        .collection('Users')
        .where('email', isEqualTo: currentUser.email)
        .get();
    
    if (querySnapshot.docs.isNotEmpty) {
      setState(() {
        _userName = querySnapshot.docs.first.data()['uname'];
        _isLoading = false;
      });
    }
  } catch (e) {
    print(e);
  }
}

注意:这种方法查询效率低于用UID直接定位,且需要额外存储邮箱字段,仅作为临时过渡方案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 05:15:41