Search code examples
flutterfirebasegoogle-signin

Troubleshooting 'setState() called after dispose()' error in Firebase authStateChanges listener in Flutter


I am using authStateChanges listner to change a signedIn user's account variable inside initState()

  @override
  void initState() {
    // Firebase userChange listener
    FirebaseAuth.instance.authStateChanges().listen((User? user) {
      if (user == null) {
        setState(() { // This is line no 43
          signedIn = false;
          userImage =
              "https://XXXX.XXXXXXXX.XXX/News-Manager/v03/static/sample_user.png";
          userName = "Guest";
        });
      } else {
        setState(() {
          signedIn = true;
          userImage = user.photoURL!;
          userName = user.displayName!;
        });
      }
    });

    // Google Sign In listener
    googleSignIn.onCurrentUserChanged.listen((GoogleSignInAccount? account) {
        setState(() {
          _currentUser = account;
        });
        if (_currentUser != null) {}
    });

    // Check if user is already signed in
    googleSignIn.signInSilently();

    super.initState();
  }

And sometimes (not always) I end up with this error:

E/flutter ( 5961): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: setState() called after dispose(): _SettingsState#60dee(lifecycle state: defunct, not mounted)
E/flutter ( 5961): This error happens if you call setState() on a State object for a widget that no longer appears in the widget tree (e.g., whose parent widget no longer includes the widget in its build). This error can occur when code calls setState() from a timer or an animation callback.
E/flutter ( 5961): The preferred solution is to cancel the timer or stop listening to the animation in the dispose() callback. Another solution is to check the "mounted" property of this object before calling setState() to ensure the object is still in the tree.
E/flutter ( 5961): This error might indicate a memory leak if setState() is being called because another object is retaining a reference to this State object after it has been removed from the tree. To avoid memory leaks, consider breaking the reference to this object during dispose().
E/flutter ( 5961): #0      State.setState.<anonymous closure> (package:flutter/src/widgets/framework.dart:1103:9)
E/flutter ( 5961): #1      State.setState (package:flutter/src/widgets/framework.dart:1138:6)
E/flutter ( 5961): #2      _SettingsState.initState.<anonymous closure> (package:kutchsetu/screens/Settings.dart:43:9)

Initially I thought this happens because Google Sign In opens a popup for account selection.

But this is not the case as error also comes when sign in is done without popup of account selection.

Other solution advice to use if(mounted) before calling setState(), but if listner not assign values as it doesn't go inside if(mounted), it will break the functionality.

Anyone aware what causes this in authChange listners?


Solution

  • The problem basically happens because your state has already been disposed. We do not know from your code what happening in the widget tree. So there is a possibility anytime your page can be disposed and you can handle this by using "mounted" property of the State class. This property will be false whenever your widget is not in the widget tree. So you can check whenever you use setState like this:

    if(mounted) {
        setState((){});
    }