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

Flutter Firebase 如何获取当前已登录用户的邮箱地址?

实现方案

前置条件

已完成Firebase Auth SDK集成,且用户登录流程正常运行。

步骤1:获取已登录用户实例

Firebase Auth会自动缓存已登录用户的信息,不需要额外异步请求即可直接读取:

// Java 版本
FirebaseAuth auth = FirebaseAuth.getInstance();
FirebaseUser currentUser = auth.getCurrentUser();
// Kotlin 版本
val auth = FirebaseAuth.getInstance()
val currentUser = auth.currentUser

getCurrentUser返回null时代表当前无已登录用户

步骤2:在Drawer头部布局中添加邮箱展示控件

通常Drawer的用户信息展示在NavigationView的头部布局中,在对应的xml布局(一般命名为nav_header_main.xml之类)新增TextView:

<TextView
    android:id="@+id/tv_user_email"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="8dp"
    android:textSize="14sp"
    android:textColor="@color/white"/>

步骤3:绑定控件并赋值邮箱

在Drawer关联的Activity/Fragment中,先获取NavigationView的头部View,再给控件赋值:

Java 实现

NavigationView navigationView = findViewById(R.id.nav_view);
// 获取第一个头部View,如果你添加了多个头部可以对应调整索引
View headerView = navigationView.getHeaderView(0);
TextView tvUserEmail = headerView.findViewById(R.id.tv_user_email);

if (currentUser != null) {
    String email = currentUser.getEmail();
    tvUserEmail.setText(email != null ? email : "未绑定邮箱");
} else {
    tvUserEmail.setText("请先登录");
}

Kotlin 实现

val navigationView = findViewById<NavigationView>(R.id.nav_view)
val headerView = navigationView.getHeaderView(0)
val tvUserEmail = headerView.findViewById<TextView>(R.id.tv_user_email)

currentUser?.apply {
    tvUserEmail.text = email ?: "未绑定邮箱"
} ?: run {
    tvUserEmail.text = "请先登录"
}

补充优化点

  • 如果应用支持切换账号、退出登录操作,建议在onResume生命周期中重复执行赋值逻辑,确保展示的信息和当前登录账号匹配
  • 若使用Jetpack Navigation组件,可以添加Auth状态监听器,监听登录状态变化时自动更新邮箱展示

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 00:15:02