创建Firebase注册函数时遇错误:Instance member 'user'无法静态访问
Flutter Firebase注册报错:Instance member 'user' can't be accessed using static access.
问题详情
开发注册功能时,执行String userId = UserCredential.user!.uid;代码时触发错误提示:Instance member 'user' can't be accessed using static access.
原代码如下:
final auth = FirebaseAuth.instance; final db = FirebaseFirestore.instance; Future<bool> register(String email, String password, String username) async { try { await FirebaseAuth.instance .createUserWithEmailAndPassword(email: email, password: password); String userId = UserCredential.user!.uid; final userRef = FirebaseFirestore.instance.collection('users').doc(userId); await userRef.set({ 'username': username, 'email': email, }); return true; } on FirebaseAuthException catch (e) { if (e.code == 'weak-password') { print('Password provided is too weak'); global.error = "Password provided is too weak"; } else if (e.code == 'email-already-in-use') { global.error = "The account already exist for that email."; print('The account already exist for that email.'); } return false; } catch (e) { print(e.toString()); return false; } }
解决方案
错误核心是:user是UserCredential的实例属性,不能直接通过类名静态访问,必须先获取createUserWithEmailAndPassword返回的实例对象,再通过实例访问user。
修改后的代码:
final auth = FirebaseAuth.instance; final db = FirebaseFirestore.instance; Future<bool> register(String email, String password, String username) async { try { // 接收createUserWithEmailAndPassword返回的UserCredential实例 UserCredential userCredential = await FirebaseAuth.instance .createUserWithEmailAndPassword(email: email, password: password); // 通过实例对象访问user属性 String userId = userCredential.user!.uid; final userRef = FirebaseFirestore.instance.collection('users').doc(userId); await userRef.set({ 'username': username, 'email': email, }); return true; } on FirebaseAuthException catch (e) { if (e.code == 'weak-password') { print('Password provided is too weak'); global.error = "Password provided is too weak"; } else if (e.code == 'email-already-in-use') { global.error = "The account already exist for that email."; print('The account already exist for that email.'); } return false; } catch (e) { print(e.toString()); return false; } }
关键修改点
- 新增
UserCredential userCredential = await ...,接收注册接口返回的实例对象 - 将
UserCredential.user!.uid改为userCredential.user!.uid,通过实例访问属性
内容的提问来源于stack exchange,提问作者Chinmay
相关产品推荐
相关产品推荐

