Flutter firebase 身份验证事件处理程序和热重载

Ant*_*Lev 5 dart firebase firebase-authentication flutter gorouter

关注此博客文章:https://blog.ishangavidusha.com/flutter-authentication-flow-with-go-router-and-provider

我已经使用 go router 实现了一个 flutter 应用程序。我已在我的 flutter 应用程序中添加了 firebase 身份验证处理程序initState()

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

在我的 authservice 类中,我有一个如下的构造函数:

 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);
      }
    });
  }
Run Code Online (Sandbox Code Playgroud)

一切正常。当我在应用程序中更改某些内容并保存更改时,应用程序会执行热重新加载。似乎热重载使前一个事件处理程序保持活动状态,因为每次热重载后,authStateChanges当我执行登录任务时,我都会再调用一次事件处理程序。热重载后,print('User is signed in!');登录后我会得到两个打印语句。每次热重载后还会有一个。

这是可以接受的开发行为还是我的应用程序架构不正确?

kuh*_*yal 2

在热重新加载期间,状态保持活动状态,因此initState重新加载后不应再次调用您的方法。您可以使用调试器或打印语句来验证这一点。

如果是,那么您的小部件树中有些东西不理想。

一种常见的模式是在此类服务类中实现dispose取消订阅的方法。然后从您的 states 方法调用它dispose来清理服务。

这是否可以接受取决于您对质量的定义。这可能意味着存在一些问题,由于一些疯狂的重建也可能在生产中发生。我强烈建议您尝试了解发生的情况并解决它。