Flutter+Firebase注册时存储UID失败问题求助及代码排查
UID存储到Firebase数据库的错误修复方案
错误根源
你代码里的致命问题是在用户完成注册前就获取auth.currentUser——调用createUserWithEmailAndPassword之前,用户账号还未创建成功,auth.currentUser处于null状态,你用!强制解包直接触发了Null check operator used on a null value异常。Firebase提示的“未登录无法获取token”错误,也是因为此时用户还没有有效登录状态导致的。
正确代码实现
必须在createUserWithEmailAndPassword的成功回调里,从返回的UserCredential对象中提取UID,而不是提前调用auth.currentUser。修改后的代码如下:
auth.createUserWithEmailAndPassword( email: emailcontroller.text.toString(), password: passcontroller.text.toString() ).then((userCredential) { // 从注册成功的返回结果中获取合法UID final uid = userCredential.user!.uid; ref.doc(uid).set({ "id": uid, "name": namecontroller.text.toString(), "email": emailcontroller.text.toString(), "phone": phonecontroller.text.toString(), "imageurl": url1.toString() }); });
重要安全与优化提示
- 禁止存储明文密码:Firebase Auth已经帮你完成了密码的加密存储,将明文密码存入数据库属于严重安全漏洞,直接删除
"password": passcontroller.text.toString()这一行。 - 推荐使用
async/await优化代码可读性:
try { final userCredential = await auth.createUserWithEmailAndPassword( email: emailcontroller.text.toString(), password: passcontroller.text.toString() ); final uid = userCredential.user!.uid; await ref.doc(uid).set({ "id": uid, "name": namecontroller.text.toString(), "email": emailcontroller.text.toString(), "phone": phonecontroller.text.toString(), "imageurl": url1.toString() }); // 注册成功后的后续逻辑,例如跳转首页 } catch (e) { // 捕获并处理注册失败的错误 print(e.toString()); }
内容的提问来源于stack exchange,提问作者Muhammad Zohaib
相关产品推荐
相关产品推荐

