简体   繁体   English

在 flutter 中的 null 上调用了 getter 'uid'

[英]The getter 'uid' was called on null in flutter

I'm implementing firebase authentication in flutter application but while trying to get user uid, it is crashing and show noSuchMethodError uid is null, if anyone could help, it is deeply appreciated我在 flutter 应用程序中实现 firebase 身份验证,但是在尝试获取用户 uid 时,它崩溃并显示 noSuchMethodError uid 是 null,如果有人能提供帮助,我们将不胜感激,

  • That's how i init my variables这就是我初始化变量的方式
class _UserRegistrationState extends State<UserRegistration> {

FirebaseAuth auth;
DocumentReference reference;
Reference storage;

PickedFile imageUri;
final ImagePicker _imagePicker = new ImagePicker();

@override
void initState() {
  super.initState();

  auth =   FirebaseAuth.instance;
   
  // the uid is where the logcat is pointing too and it is null
  reference =  FirebaseFirestore.instance.collection('users').doc(auth.currentUser.uid);
  storage =  firebase_storage.FirebaseStorage.instance.ref('avatar').child(auth.currentUser.uid);
}

currentUser → User?当前用户→用户? Returns the current User if they are currently signed-in, or null if not.如果当前用户当前已登录,则返回当前用户,否则返回 null。

So most likely thing is that you are not logged in and therefore passing null to reference所以最有可能的是您没有登录,因此将 null 传递给reference

When you sign in to Firebase Authentication, the SDK automatically persists the user's credentials in local storage.当您登录 Firebase 身份验证时,SDK 会自动将用户的凭据保存在本地存储中。 When you restart the app, the SDK tries to restore the user's authentication state from the stored credentials.当您重新启动应用程序时,SDK 会尝试从存储的凭据中恢复用户的身份验证 state。 This requires that it calls the servers to get a new ID token, and for example to check if the account was deleted/disabled in the meantime.这要求它调用服务器以获取新的 ID 令牌,例如检查帐户是否同时被删除/禁用。

Depending on the platform where you run your code, the calls to the server may have completed before your auth.currentUser runs, or not.根据您运行代码的平台,对服务器的调用可能在您的auth.currentUser运行之前完成,也可能没有。 To safely respond to the user state, always use an auth state listener as shown in the FlutterFire documentation on responding to auth state changes :为了安全地响应用户 state,请始终使用身份验证 state 侦听器,如 FlutterFire 文档中关于响应身份验证 state 更改中所示:

@override
void initState() {
  super.initState();

  auth = FirebaseAuth.instance;
   
  FirebaseAuth.instance.authStateChanges().listen((User user) {
    if (user == null) {
      print('User is currently signed out!');
    } else {
      print('User is signed in!');
      reference =  FirebaseFirestore.instance.collection('users').doc(auth.currentUser.uid);
      storage =  firebase_storage.FirebaseStorage.instance.ref('avatar').child(auth.currentUser.uid);
    }
  });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM