Flutter Firebase获取当前登录用户数据并展示到Profile页面的实现方案
核心问题根源
你当前实现的最大问题是Firestore的用户文档完全未和登录用户的身份标识绑定:
- 注册写入时用
add()方法生成随机文档ID,没有和当前登录用户的Firebase Auth UID建立映射 - 拉取数据时不得不扫描整个users集合匹配用户,效率极低且无法精准定位
提示:你当前使用的依赖均为2019-2020年的旧版本,以下所有代码写法100%匹配对应版本的API,无需升级依赖即可直接运行。
第一步:修正用户数据写入逻辑
替换原有的随机ID写入逻辑,将Firestore中users集合的文档ID直接设置为当前登录用户的UID,从根源建立身份和数据的映射关系:
// 适配旧版cloud_firestore、firebase_auth API的写入方法 void createRecord(name, email, password) async { // 获取当前已登录的Firebase认证用户对象 FirebaseUser currentUser = await FirebaseAuth.instance.currentUser(); // 以用户UID为文档ID写入数据,替代原随机ID的add()写法 await databaseReference .collection("users") .document(currentUser.uid) .setData({ 'name': name, 'email': email, 'password': password, }); }
安全提醒:明文存储用户密码到Firestore存在严重的安全隐患,Firebase Auth已经完成了用户认证信息的加密托管,无需额外将密码字段写入Firestore集合。
第二步:替换全量拉取的getData方法
文档ID与UID绑定后,无需遍历全量集合,可直接定位当前用户的单文档拉取数据,查询效率从全量扫描降为单文档直查:
Map<String, dynamic> currentUserData = {}; Future<void> getCurrentUserData() async { try { // 校验用户登录状态 FirebaseUser currentUser = await FirebaseAuth.instance.currentUser(); if (currentUser == null) return; // 直接按UID定位单文档 DocumentSnapshot userSnapshot = await databaseReference .collection("users") .document(currentUser.uid) .get(); // 读取文档数据 if (userSnapshot.exists) { currentUserData = userSnapshot.data; print("当前登录用户数据:$currentUserData"); } } catch (e) { print("数据拉取失败:$e"); } }
第三步:结合provider实现数据到UI的渲染
适配你使用的provider: ^3.1.0版本的API,通过状态管理将拉取到的用户数据同步到Profile页面,避免手动setState的冗余逻辑:
- 首先创建适配版本的状态管理类
import 'package:flutter/foundation.dart'; // 适配provider 3.1.0的ChangeNotifier class UserProfileProvider extends ChangeNotifier { Map<String, dynamic> _userData = {}; Map<String, dynamic> get userData => _userData; bool _isLoading = false; bool get isLoading => _isLoading; Future<void> loadCurrentUserData() async { _isLoading = true; notifyListeners(); // 通知UI展示加载状态 try { FirebaseUser currentUser = await FirebaseAuth.instance.currentUser(); if (currentUser == null) return; DocumentSnapshot snapshot = await Firestore.instance .collection("users") .document(currentUser.uid) .get(); if (snapshot.exists) { _userData = snapshot.data; } } catch (e) { debugPrint("用户数据拉取异常:$e"); } _isLoading = false; notifyListeners(); // 通知UI刷新最终数据 } }
- 在应用根节点注入Provider
void main() { runApp( ChangeNotifierProvider<UserProfileProvider>( create: (context) => UserProfileProvider(), child: MyApp(), ), ); }
- Profile页面的数据渲染逻辑
class ProfilePage extends StatefulWidget { @override _ProfilePageState createState() => _ProfilePageState(); } class _ProfilePageState extends State<ProfilePage> { @override void initState() { super.initState(); // 页面初始化时触发数据拉取 Future.microtask(() { Provider.of<UserProfileProvider>(context, listen: false) .loadCurrentUserData(); }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text("个人资料")), body: Consumer<UserProfileProvider>( builder: (context, provider, child) { // 加载态处理 if (provider.isLoading) { return const Center(child: CircularProgressIndicator()); } // 渲染用户信息 return Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text( "姓名:${provider.userData['name'] ?? '信息缺失'}", style: const TextStyle(fontSize: 18), ), const SizedBox(height: 16), Text( "邮箱:${provider.userData['email'] ?? '信息缺失'}", style: const TextStyle(fontSize: 18), ), ], ), ); }, ), ); } }
额外注意事项
- 原
createRecord方法如果已经生成了一批随机ID的历史用户文档,需要做一次数据迁移,将旧文档的ID修改为对应用户的UID,否则旧用户数据无法被精准匹配 - 所有方法调用都做了登录态校验,避免未登录状态下拉取数据触发的空指针异常
内容的提问来源于stack exchange,提问作者wensian
相关产品推荐
相关产品推荐

