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

Flutter中如何获取Firestore中当前用户文档的gender属性?

解决方案:获取当前用户的Firestore性别信息

要实现根据当前登录用户动态获取对应的gender属性,核心是用当前用户的UID替换硬编码的文档ID,具体步骤和修改后的代码如下:

关键修改点

  • 获取当前Firebase认证用户的UID,作为Firestore文档的查询ID
  • 处理用户未登录的边界情况

修改后的完整代码

import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_firestore/firebase_firestore.dart';
import 'package:flutter/material.dart';

class _ProfileScreenState extends State<ProfileScreen> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: FutureBuilder<Profiles?>(
      future: readCurrentUser(),
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return const Center(child: CircularProgressIndicator());
        }
        
        if (snapshot.hasError) {
          return Center(child: Text('加载出错: ${snapshot.error}'));
        }

        final user = snapshot.data;

        if (user == null) {
          // 处理用户未登录或文档不存在的情况
          return const Center(child: Text('请先登录'));
        }

        return buildUser(user);
      },
    ));
  }

  Future<Profiles?> readCurrentUser() async {
    // 获取当前登录用户
    final currentUser = FirebaseAuth.instance.currentUser;
    if (currentUser == null) {
      return null; // 用户未登录,返回null
    }

    // 使用当前用户UID查询对应的profiles文档
    final docUser = FirebaseFirestore.instance
        .collection('profiles')
        .doc(currentUser.uid);

    final snapshot = await docUser.get();

    if (snapshot.exists) {
      return Profiles.fromJson(snapshot.data()!);
    }
    return null;
  }

  Widget buildUser(Profiles profile) => ListTile(
        title: Text(profile.gender),
      );
}

注意事项

  1. 注册时的文档ID规范:确保用户注册时,你是用FirebaseAuth.instance.currentUser?.uid作为profiles集合的文档ID来存储用户信息,这样才能通过UID匹配到对应的文档。
  2. 未登录状态处理:如果用户未登录,currentUser会返回null,此时可以根据业务需求跳转到登录页面,或者显示提示文本。
  3. 错误处理:代码中增加了错误状态的判断,避免加载过程中出现未处理的异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 01:02:29