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

Flutter中如何从Firebase获取当前登录用户信息展示在导航栏

Flutter 从Firebase获取登录用户信息并展示在导航栏实现方案

你现有代码已经完成了Firebase Auth登录、Firestore拉取用户数据的核心逻辑,问题在于获取到的用户数据没有传递给NavBar组件,导致导航栏只能显示写死的"Test"占位文本,按以下步骤修改即可:


1. 修改navbar.dart,增加用户数据入参

给NavBar组件增加必填的用户模型参数,替换原来写死的账号名称、邮箱文本,同时增加空值兜底避免异步加载阶段报错:

import 'package:flutter/material.dart';
import '../model/user_model.dart';

class NavBar extends StatelessWidget {
  // 新增接收登录用户数据的参数
  final UserModel loggedInUser;
  const NavBar({Key? key, required this.loggedInUser}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Drawer(
      child: ListView(
        padding: EdgeInsets.zero,
        children: [
          UserAccountsDrawerHeader(
            // 替换原来的硬编码Test,拼接姓和名作为显示名,空值时显示加载中
            accountName: Text(
              loggedInUser.firstName != null 
                ? "${loggedInUser.firstName} ${loggedInUser.secondName ?? ''}"
                : "加载中..."
            ),
            // 替换硬编码邮箱,空值兜底
            accountEmail: Text(loggedInUser.email ?? "加载中..."),
            currentAccountPicture: CircleAvatar(
              child: ClipOval(
                child: Image.network(
                  'https://sunrift.com/wp-content/uploads/2014/12/Blake-profile-photo-square.jpg',
                  width: 90,
                  height: 90,
                  fit: BoxFit.cover,
                ),
              ),
            ),
            decoration: const BoxDecoration(
                color: Colors.blue,
                image: DecorationImage(
                  image: NetworkImage(
                    "https://blog.depositphotos.com/wp-content/uploads/2017/07/Soothing-nature-backgrounds-2.jpg.webp",
                  ),
                  fit: BoxFit.cover,
                )),
          ),
          // 下方原有ListTile代码保持不变即可
          ListTile(
            leading: const Icon(Icons.home),
            title: const Text("Anasayfa"),
            onTap: () => null,
          ),
          ListTile(
            leading: const Icon(Icons.people),
            title: const Text("Kullanıcılar"),
            onTap: () => null,
          ),
          ExpansionTile(
            leading: const Icon(Icons.document_scanner_rounded),
            title: const Text('Raporlar'),
            children: <Widget>[
              Container(
                margin: const EdgeInsets.only(left: 10.0),
                child: ListTile(
                  leading: const Icon(Icons.document_scanner_outlined),
                  title: const Text('Günlük Rapor'),
                  onTap: () => null,
                ),
              ),
              Container(
                margin: const EdgeInsets.only(left: 10.0),
                child: ListTile(
                  leading: const Icon(Icons.document_scanner_outlined),
                  title: const Text('Haftalık Rapor'),
                  onTap: () => null,
                ),
              ),
              Container(
                margin: const EdgeInsets.only(left: 10.0),
                child: ListTile(
                  leading: const Icon(Icons.document_scanner_outlined),
                  title: const Text('Aylık Rapor'),
                  onTap: () => null,
                ),
              ),
            ],
          ),
          ExpansionTile(
            leading: const Icon(Icons.question_answer),
            title: const Text('Talepler'),
            children: <Widget>[
              Container(
                margin: const EdgeInsets.only(left: 10.0),
                child: ListTile(
                  leading: const Icon(Icons.question_answer_outlined),
                  title: const Text('İzin Talepleri'),
                  onTap: () => null,
                ),
              ),
              Container(
                margin: const EdgeInsets.only(left: 10.0),
                child: ListTile(
                  leading: const Icon(Icons.request_page_outlined),
                  title: const Text('Avans Talepleri'),
                  onTap: () => null,
                ),
              ),
            ],
          ),
          ListTile(
            leading: const Icon(Icons.track_changes),
            title: const Text("Mesai Takip"),
            onTap: () => null,
          ),
          ListTile(
            leading: const Icon(Icons.notifications),
            title: const Text("Duyuru Ekle"),
            onTap: () => null,
          ),
          ListTile(
            leading: const Icon(Icons.person),
            title: const Text("Profil"),
            onTap: () => null,
          ),
          ListTile(
            leading: const Icon(Icons.exit_to_app),
            title: const Text("Exit"),
            onTap: () => null,
          ),
        ],
      ),
    );
  }
}

2. 修改home.dart,将拉取到的用户数据传入NavBar

你原来已经在initState里拉取了Firestore的用户数据,只需要在构建NavBar的时候把数据传进去即可,同时补全文档存在性判断避免空报错:

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebaseAuth.dart';
import 'package:flutter/material.dart';
import 'navbar.dart';
import '../model/user_model.dart';

void main(List<String> args) {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: const MyHomePage(),
    );
  }
}

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

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  User? user = FirebaseAuth.instance.currentUser;
  UserModel loggedInUser = UserModel();

  @override
  void initState() {
    super.initState();
    // 拉取用户数据时增加异常和存在性判断
    if (user != null) {
      FirebaseFirestore.instance
          .collection("users")
          .doc(user!.uid)
          .get()
          .then((value) {
        if (value.exists) {
          loggedInUser = UserModel.fromMap(value.data());
          setState(() {});
        }
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // 把获取到的loggedInUser传给NavBar组件
      drawer: NavBar(loggedInUser: loggedInUser),
      appBar: AppBar(
        title: const Text("Anasayfa"),
      ),
      body: const Center(),
    );
  }
}

注意事项

  • 你贴出的user_model.dart重复了两次,现有模型逻辑不需要修改,可以正常使用
  • login-screen.dart现有登录逻辑不需要修改,登录成功跳转的逻辑正常
  • 确保注册用户时,已经将uid、email、firstName、secondName字段写入Firestore的users集合下对应用户uid的文档中,否则会出现字段为空的情况
  • 异步加载用户数据的几百毫秒内,导航栏会显示"加载中..."占位,数据拉取完成后会自动刷新显示真实用户名和邮箱

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 00:21:51