'Flutter firebase authentication event handler and hot reloads

Following this blog post: https://blog.ishangavidusha.com/flutter-authentication-flow-with-go-router-and-provider

I have implemented a flutter app using the go router. I have added the firebase authentication handler in the initState() of my flutter App:

 @override
  void initState() {
    appService = AppService(widget.sharedPreferences);
    authService = AuthService();
    authSubscription = authService.onAuthStateChange.listen(onAuthStateChange);
    super.initState();
  } 

Here in my authservice class, I have a constructor like this:

 AuthService() {
    authSubscription =
        FirebaseAuth.instance.authStateChanges().listen((User? user) {
      if (user == null) {
        //appService.loginState = false;
        print('User is currently signed out!');
        _onAuthStateChange.add(false);
      } else {
        //appService.loginState = true;
        print('User is signed in!');
        _onAuthStateChange.add(true);
      }
    });
  }

Everything works fine. When I change something in my app and save the changes, the app performs a hot reload. It seems like the hot reload keeps the previous event handler active as after each hot reload, I have one more call to my authStateChanges event handler when I perform a login task. After a hot reload I would have two print statement print('User is signed in!'); after a login. And one more after each hot reload.

Is this acceptable behavior for development or is my app not architected correctly?



Solution 1:[1]

During a hot reload the state stays alive, so your initState method should not be called again after the reload. You can verify this with the debugger or a print statement.

If it is, then something is not ideal in the your widget tree.

A common pattern is to implement a dispose method in such a service class which cancels the subscription. Then call it from your states dispose method to cleanup the service.

If this is acceptable depends on your definition of quality. It likely means there is something wrong which due to some wild rebuild can also happen in production. I strongly recommend you to try to understand what is happening and fix it.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 kuhnroyal