What is Wrong With My InitState in Flutter?

Issue

I am trying to do autologin with flutter and firebase and put it in an initState but it doesn’t seem to be excuted because I tried to move it to Build Widget but nothing worked but when I put it inside LoginPageState It was excuted but with error :
Navigator operation requested with a context that does not include a Navigator.
My Code :

@override
  void initState() {
    super.initState();
    final user = FirebaseAuth.instance.currentUser();
    if (user == null) {
      print('User Null');
    } else {
      Navigator.pushReplacementNamed(context, '/HomePage');
    }
  }

Solution

You need to wait for the FirebaseAuth.instance.currentUser() to finish. So use await as the following.

final user = await FirebaseAuth.instance.currentUser()

Answered By – Sanjay Sharma

Answer Checked By – Timothy Miller (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *