skip to Main Content

I have been using userCredential.additionalUserInfo!.isNewUser to check if the user is new but this method has a huge downside which i will explain.
In my app, I want to check if the user is new then if yes I will direct him to profile info page otherwise, he will be directed to different page. with this method (isNewUser), the first time the user sign in, it will work fine but if the user sign in for the first time then for some reason he close the app or signout before submitting the profile page, the next time he sign in he will not be treated as new user and he will not be directed to the profile page.

I came up with a way that does work but it also has its downside.

  bool isExictedUser=false;


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

  }

Future<void> checkIfUserHasData () async { // to check if the user has submitted a profile form before by checking if he has a name stored in the DB

    var data = await FirebaseFirestore.instance
        .collection('users')
        .doc(userID)
        .collection('personalInfo').doc(documentID)
        .get().then((value) {
         setState(() {
         name = value.get('name');

         });
    });
    if (name != null){
      setState((){
        isExictedUser = true;
      });
    }else {
      return;
    }
  }


 Widget build(BuildContext context) => isExictedUser
      ? const HomeScreen()
      :
     WillPopScope(
    onWillPop: _onBackPressed,
     child: Scaffold(

The problem with my method is that it takes few seconds to finish so even if the user is not new he will first be directed to the profile page for like 2 seconds until it confirm that he has a name stored.

Is there a way to optimize the (additionalUserInfo!.isNewUser) method or an alternative to keep showing the profile page until the user submit the form?

3

Answers


  1. I usually keep a users’ list in a Firebase database and manage users there.

    Whenever a user authentication success, I input the same username into one of the databases (either Firestore or the Realtime Database) in firebase. Now this database can be used to check existing users.

    Keep in mind that this part of the database should be open without any security rules so that it can be used before authentication.

    Login or Signup to reply.
  2. You can use FutureBuilder widget:

    class MyFutureWidget extends StatelessWidget{
    
        @override
        Widget build(BuildContext context){
            return FutureBuilder<FirebaseUser>(
                future: FirebaseAuth.instance.currentUser(),
                builder: (BuildContext context, AsyncSnapshot<FirebaseUser> snapshot){
                           if (snapshot.hasData){
                               FirebaseUser user = snapshot.data; // this is your user instance
                               /// is because there is user already logged
                               return MainScreen();
                            }
                             /// other way there is no user logged.
                             return LoginScreen();
                 }
              );
        }
    }
    

    For more information you can refer Documentation, stackoverflow thread, Firebase auth.

    Login or Signup to reply.
  3. One other way to check whether the user is a new user or not is to check inside AdditionalUserInfo.
    Field detail

    Below is the code example of firebase phone authentication but the same can be replicated to other forms of authentication also.

     PhoneAuthCredential credential =
                            PhoneAuthProvider.credential(
                                verificationId: verificationId,
                                smsCode: smsCode);
                          
                            UserCredential userCred =
                            await auth.signInWithCredential(credential);
                            bool? isNewUser = userCred.additionalUserInfo?.isNewUser;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search