在 Flutter 中获取 Firebase 用户 ID 时共享首选项 returns 启动时为空

Shared Preferences returns null on startup when fetching Firebase user ID in Flutter

我在用户登录时获取我的用户 ID,并将其存储在我登录页面的共享首选项中,就像这样

 Future<FirebaseUser> _register() async {

// ... Firebase Login Code

SharedPreferences prefs = await SharedPreferences.getInstance();
 if (user != null) {
          // Check is already sign up
          final QuerySnapshot result = await Firestore.instance
              .collection('users')
              .where('id', isEqualTo: user.uid)
              .getDocuments();
          final List<DocumentSnapshot> documents = result.documents;
          if (documents.length == 0) {
            // Update data to server if new user
            Firestore.instance.collection('users').document(user.uid).setData({
              'id': user.uid,
              'name': user.displayName
            });
            currentUser = user;
            await prefs.setString('id', currentUser.uid);
            await prefs.setString('name', currentUser.displayName);
          } else {
            await prefs.setString('id', documents[0]['id']);
            await prefs.setString('name', documents[0], ['name']);
          }
        }

}

然后我将用户传递到我的主屏幕,如果用户不为空,则在用户进入首页后,shared prefs 收到的用户ID 为空, 我正在从 initState()

中获取用户 ID
void initState() {
fetchName();
}

fetchName() async {
      SharedPreferences prefs = await SharedPreferences.getInstance();
      userTestName = prefs.getString('name') ?? '';
    id = prefs.getString('id') ?? '';

    }

问题 #1 在我关闭应用程序并重新启动它后,我的用户 ID 被检索并且我可以显示我的用户名但是我无法在用户第一次登录应用程序时实现这一点。

问题 #2 如果我注销我的用户,并将用户重新登录到存储在共享首选项中的 ID 仍然是以前的值,登录时调用旧用户的 ID,然后在重新启动应用程序时获取新用户的 ID。

我尝试查看其他 Stack Overflow 页面,但我仍然很困惑并且是 Flutter 的新手!

为什么在使用 Firebase 时使用 SharedPreferences ?? 当您的应用程序启动时,您可以直接从 FirebaseAuth 对象访问登录的用户详细信息。

    FirebaseUser loggedUser;
    checkLoggedIn() {
        FirebaseAuth.instance.currentUser().then((FirebaseUser user) {
          if (user != null ) {
             loggedUser = user;
             setState(() {});
             // all these values may or may not be null that depends if the user's 
             // login provider has got these details from user or not
             //user.providerId;// access the logged in userId
             //user.displayName;// access logged in user Name
             //user.email;// access logged in user email
             //user.phoneNumber;// access logged in user contact number 
          }
        });
      }

调用 checkLoggedIn() 方法 在有状态小部件的 initState() 函数中

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