why firebase auth can't recognize the logged in user after the app is removed from task?

Viewed 46

i am trying to make sure the app knows if the user is logged in or not. if they are logged in, then they are redirected to the home page. if not they are brought to the landing page.

the app seems to work fine if i just restart the entire app or just close the app without removing it from task. however if i remove close the app and remove the app from task. it brings me to the landing page while, in fact, the user is still logged in.

the following is what i use to determine if the user is logged in, if so they are redirected to the home page, otherwise, landing page.

class LandingOrHome extends StatefulWidget {
  @override
  _LandingOrHomeState createState() => _LandingOrHomeState();
}

class _LandingOrHomeState extends State<LandingOrHome> {


  var onlineCurrentUser;

  FirebaseUser getCurrentUser() {

    FirebaseAuth.instance.currentUser().then((currentUser) {
      if (currentUser != null) {
        onlineCurrentUser = currentUser;
      }
    });

    if (onlineCurrentUser != null) return onlineCurrentUser;
    return null;
  }

  @override
  Widget build(BuildContext context) {
    if (getCurrentUser() != null)
      return HomeScreen();
    else
      return LandingScreen();
  }
}

main.dart

 //...
    home: LandingOrHome()
1 Answers

As far I can tell, the problem is that getCurrentUser is not waiting for FirebaseAuth to finish so it will be always null the first time.

Use a FutureBuilder to build your widget based on a future result

class LandingOrHome extends StatefulWidget {
  @override
  _LandingOrHomeState createState() => _LandingOrHomeState();
}

class _LandingOrHomeState extends State<LandingOrHome> {
  Future<FirebaseUser> getCurrentUserFuture;

  @override
  void initState() {
    // Future needs to be built before build, if you do it on build it will be executed every time the widget is recreated
    getCurrentUserFuture = getCurrentUser();
    super.initState();
  }

  Future<FirebaseUser> getCurrentUser() => FirebaseAuth.instance.currentUser();

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
        future: getCurrentUserFuture,
        builder: (context, snapshot){
          if (!snapshot.hasData) {
            // data is being loaded, return a loading indicator or something
            // to let the user know that something is in progress
          }

          if (snapshot.data != null)
            return HomeScreen();
          else
            return LandingScreen();
        });
  }
}
Related