[Unhandled Exception: setState() called after dispose(): LoginScreenState#ebb98(lifecycle state: defunct, not mounted)

Viewed 23

I have my loginStateSubscription to see If user sign in or not But the problem is when I try to logout of the app. It indicated to this error [Unhandled Exception: setState() called after dispose(): LoginScreenState#ebb98(lifecycle state: defunct, not mounted)

Login Screen:

 @override
  void initState() {
    final authBloc = Provider.of<AuthBloc>(context, listen: false);
    loginStateSubscription = authBloc.currentUser.listen((fbUser) {
      if (fbUser != null) {
          if(mounted) {
            Navigator.pushAndRemoveUntil(
              context,
              MaterialPageRoute(builder: (_) => const HomeScreen()),
              (route) => false);
          }
        
      }
    });
    super.initState();
  }

  @override
  void dispose() {
    loginStateSubscription.cancel();
    super.dispose();
  }

Log out button:

               ElevatedButton(
                     onPressed: () async {
                           await logout1();
                          },
1 Answers
if(mounted) {
  Navigator.pushAndRemoveUntil(
    context,
    MaterialPageRoute(builder: (_) => const HomeScreen()),
    (route) => false);
}else{
 return;
}
Related