How to check if the user is logged in, if so show other screen?

后端 未结 3 590
夕颜
夕颜 2021-02-01 06:08

My first screen is a login screen and it needs to check if the user is logged in to open the home screen directly but I get an error using this check.

I\'m doing the che

3条回答
  •  暖寄归人
    2021-02-01 06:34

    Well you can solve this kind of problem using another approach. Instead check if there is user logged inside your loginScreen class you can do this a step before and then decide if you will show the loginScreen if there is no user logged or show another screen, MainScreen I' am supposing, if the user is already logged.

    I will put some snipet showing how to accomplish this. I hope it helps. But before I will explain you what is wrong in your source code.

    if(FirebaseAuth.instance.currentUser() != null){
          // wrong call in wrong place!
          Navigator.of(context).pushReplacement(MaterialPageRoute(
            builder: (context) => HomeScreen()
          ));
    }
    

    Your code is broken because currentUser() is a async function and when you make the call this function is returning a incomplete Future object which is a non null object. So the navigator pushReplacement is always been called and it's crashing because the state of your widget is not ready yet.

    Well as solution you can user FutureBuilder and decide which screen you will open.

    int main(){
       runApp(  YourApp() )
    }
    
    class YourApp extends StatelessWidget{
    
        @override
        Widget build(BuildContext context){
            return FutureBuilder(
                future: FirebaseAuth.instance.currentUser(),
                builder: (BuildContext context, AsyncSnapshot 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();
                 }
              );
        }
    }
    

    Using this approach you avoid your LoginScreen class to verify if there is a user logged!

    As advise you can make use of snapshot.connectionState property with a switch case to implement a more refined control.

提交回复
热议问题