Flutter集成新版Firebase时用户uid赋值异常、始终返回null的问题解决
问题根因
- 新版
firebase_auth插件(0.18.0及以上版本)对接口做了 Breaking Change:currentUser从异步方法改为同步属性,旧写法FirebaseAuth.instance.currentUser().then(...)已完全废弃,你跟着的YouTube教程一般基于0.17及更早的旧版本插件开发,因此原代码完全失效。 - 你把获取当前用户的逻辑放在
build方法中执行,时机完全错误:注册流程尚未执行完成时,本身就没有已登录的用户,全局变量courantUser始终为null。 - 注册流程中错误依赖提前获取的
_idUtil()生成文档id:此时用户尚未创建完成,只能拿到占位字符串"pas d'utilisateurs courant",根本不是真实的uid。 - 原有注册失败的判断逻辑完全反了:
result == null时本该重置加载状态,你却把chargement设为true,会导致页面永久卡在加载状态。
正确实现步骤
- 删除
build方法中那段废弃、时机错误的获取用户逻辑。 - 直接从
createUserWithEmailAndPassword的返回值中提取新创建用户的uid,不需要依赖提前缓存的全局用户变量。 - 修正注册失败的逻辑判断,异常场景下重置加载状态。
- 后续需在已登录场景下获取当前用户uid时,直接同步调用
FirebaseAuth.instance.currentUser?.uid即可,无需异步等待。
关键代码修改示例
首先移除build方法内的废弃代码:
// 直接删除这段无意义的错误逻辑 FirebaseAuth.instance.currentUser().then((User util){ setState(() { this.courantUser = util; }); });
修正注册按钮的onPressed逻辑:
FlatButton( onPressed: () async { if (_formKey.currentState.validate()){ setState(() { chargement = true; }); try { // 执行邮箱密码注册 UserCredential result = await _auth.createUserWithEmailAndPassword( email: email, password: motDePasse ); // 直接从返回的凭证中取真实uid String realUid = result.user?.uid ?? ''; // 写入Firestore用户文档 await collectionUtil.doc(realUid).set({ 'idUtil' : realUid, 'pseudo' : pseudo, 'email' : email }); // 注册成功后的页面跳转/状态切换逻辑可补充在这里 } catch (e) { // 捕获注册异常,重置加载状态 setState(() { chargement = false; }); } } }, color: Colors.blueAccent, child: Text("S'inscrire"), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(20.0) ), )
已登录场景下获取当前用户uid的通用写法:
// 直接同步获取,不需要Future、不需要then String? uid = FirebaseAuth.instance.currentUser?.uid;
内容的提问来源于stack exchange,提问作者StiKx
相关产品推荐
相关产品推荐

