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

Flutter如何从Firestore读取用户姓名并显示在抽屉头部?

问题描述

我是Firebase新手,注册页面收集了用户的名字、姓氏、邮箱、年龄和密码,除密码外的所有数据已存入Firestore。现在我想将这些数据中的名字和姓氏显示在Flutter首页的抽屉头部,以下是我的相关代码,请提供易懂的实现方法。

注册页代码

else {
  await FirebaseAuth.instance
      .createUserWithEmailAndPassword(
          email: emailController.text,
          password: passwordController.text)
      .then((value) async {
    Navigator.pop(context); // 关闭加载弹窗
    await FirebaseFirestore.instance
        .collection('users')
        .doc(value.user!.uid)
        .set({
      'First Name': firstNameController.text,
      'last Name': lastNameController.text,
      'email': emailController.text,
      'age': int.parse(ageController.text),
      "uID": value.user!.uid
    });
  });
}

--------

Future addUserDetails(
    String firstName, String lastName, String email, String age) async {
  await FirebaseFirestore.instance.collection('users').add({
    'First Name': firstName,
    'last Name': lastName,
    'email': lastName, // 注意:这里你写错了,应该是email而不是lastName
    'age': age
  });
}

首页抽屉代码

drawer: Drawer(
  child: ListView(
    children: <Widget>[
      DrawerHeader(
        decoration: BoxDecoration(
          color: Colors.black,
        ),
        child: Stack(
          children: <Widget>[
            
            Align(
              alignment: Alignment.centerRight + 
                Alignment(-0.7,0),

             // 此处需显示名字
               child: Text(
                'Ryan',
                style: GoogleFonts.lexendDeca(
                    textStyle:
                        TextStyle(color: Colors.white, 
                fontSize:17)),
              ),
            ),
            
            Align(
              alignment: Alignment.centerRight + 
           Alignment(-0.7,.3),

         // 此处需显示姓氏
              child: Text(
                'Gosling',
                style: GoogleFonts.lexendDeca(
                    textStyle:
                        TextStyle(color: Colors.white, fontSize: 17)),
              ),
            ),
          ],
        ),
      ),
    ],
  ),
),

Firestore数据截图

Firestore数据截图


实现方法

核心思路

你的注册代码已经把用户数据以当前用户UID为文档ID存在了users集合里,所以只需三步实现需求:

  1. 获取当前登录用户的UID
  2. 通过UID从Firestore拉取对应的用户数据
  3. 在抽屉头部动态渲染名字和姓氏

具体步骤

1. 确认依赖配置

确保pubspec.yaml中已添加必要依赖(版本号以最新为准):

dependencies:
  flutter:
    sdk: flutter
  firebase_auth: ^4.16.0
  cloud_firestore: ^4.15.0

执行flutter pub get完成依赖安装。

2. 将首页改为StatefulWidget

因为需要异步获取数据并更新UI,首页需使用StatefulWidget:

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // 页面其他代码...
      drawer: _buildDrawer(),
    );
  }

  Drawer _buildDrawer() {
    // 抽屉代码将写在这里
  }
}

3. 用FutureBuilder实现动态渲染

在抽屉头部使用FutureBuilder处理异步数据加载,同时覆盖加载、错误、空数据等场景:

Drawer _buildDrawer() {
  return Drawer(
    child: ListView(
      children: <Widget>[
        DrawerHeader(
          decoration: const BoxDecoration(color: Colors.black),
          child: FutureBuilder<DocumentSnapshot>(
            // 拉取当前用户的Firestore文档
            future: FirebaseFirestore.instance
                .collection('users')
                .doc(FirebaseAuth.instance.currentUser!.uid)
                .get(),
            builder: (context, snapshot) {
              // 数据加载中
              if (snapshot.connectionState == ConnectionState.waiting) {
                return const Center(
                  child: CircularProgressIndicator(color: Colors.white),
                );
              }

              // 加载出错
              if (snapshot.hasError) {
                return const Text('加载失败', style: TextStyle(color: Colors.white));
              }

              // 数据加载完成,解析并渲染
              if (snapshot.hasData && snapshot.data!.exists) {
                final userData = snapshot.data!.data() as Map<String, dynamic>;
                final firstName = userData['First Name'] ?? '未知';
                final lastName = userData['last Name'] ?? '用户';

                return Stack(
                  children: <Widget>[
                    Align(
                      alignment: Alignment.centerRight + const Alignment(-0.7, 0),
                      child: Text(
                        firstName,
                        style: GoogleFonts.lexendDeca(
                          textStyle: const TextStyle(color: Colors.white, fontSize: 17),
                        ),
                      ),
                    ),
                    Align(
                      alignment: Alignment.centerRight + const Alignment(-0.7, 0.3),
                      child: Text(
                        lastName,
                        style: GoogleFonts.lexendDeca(
                          textStyle: const TextStyle(color: Colors.white, fontSize: 17),
                        ),
                      ),
                    ),
                  ],
                );
              }

              // 未找到用户数据
              return const Text('未找到用户信息', style: TextStyle(color: Colors.white));
            },
          ),
        ),
        // 抽屉其他列表项...
      ],
    ),
  );
}

额外提示

  • 你的addUserDetails方法用add()生成随机文档ID,但注册时已经用set(doc(uid))存了一份以UID为ID的用户数据,两者不要混用,否则会产生重复数据。建议保留注册时的set逻辑,删除或注释addUserDetails方法。
  • 实际项目中要处理FirebaseAuth.instance.currentUser为空的情况(比如用户未登录),可跳转到登录页。
  • 可将获取用户数据的逻辑抽成单独方法,让代码更整洁:
Future<Map<String, dynamic>?> getUserData() async {
  final currentUser = FirebaseAuth.instance.currentUser;
  if (currentUser == null) return null;
  final doc = await FirebaseFirestore.instance.collection('users').doc(currentUser.uid).get();
  return doc.exists ? doc.data() as Map<String, dynamic> : null;
}

之后在FutureBuilder中使用future: getUserData()即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 01:18:09