【问题标题】:How do I logout a user from Firebase when closing the app in Flutter在 Flutter 中关闭应用程序时如何从 Firebase 注销用户
【发布时间】:2022-01-11 06:01:00
【问题描述】:

出于安全原因,我有一个应用无法保持用户身份的 firebase 身份验证,但我找不到在应用关闭或强制关闭时注销用户的方法。

我正在使用侦听器将用户导航到下一页,但是,当我打开应用程序时,它会自动导航到记录的页面。

 Future<StreamSubscription<User?>> listenUserChanges(
      GlobalKey<NavigatorState> navigatorKey) async {
    final sub = auth.userChanges().listen((event) async {
      if (event != null) {
        final token = await getUserId();
        await storage.setToken(token);
        navigatorKey.currentState!.pushReplacementNamed('/logged');
      } else {
        await storage.removeToken();
      }
    });
    return sub;
  }

【问题讨论】:

    标签: firebase flutter dart firebase-authentication


    【解决方案1】:

    使用 WidgetsBindingObserver 来做你的事情。用 AppLifeCycleManager() 包装 MaterialApp

    class AppLifeCycleManager extends StatefulWidget {
      final Widget child;
      final MyUserRepository myUserRepo;
    
      const AppLifeCycleManager(
          {Key? key, required this.child, required this.myUserRepo})
          : super(key: key);
    
      @override
      _AppLifeCycleManagerState createState() => _AppLifeCycleManagerState();
    }
    
    class _AppLifeCycleManagerState extends State<AppLifeCycleManager>
        with WidgetsBindingObserver {
      @override
      void initState() {
        super.initState();
    
        widget.myUserRepo.setOnlineCustomer();
        WidgetsBinding.instance!.addObserver(this);
    
      }
    
      @override
      Future<void> didChangeAppLifecycleState(AppLifecycleState state) async {
        super.didChangeAppLifecycleState(state);
    
        switch (state) {
          case AppLifecycleState.paused:
            widget.myUserRepo.setInactiveCustomer();
            break;
          case AppLifecycleState.resumed:
            widget.myUserRepo.setOnlineCustomer();
            break;
          case AppLifecycleState.inactive:
            widget.myUserRepo.setInactiveCustomer();
            break;
          case AppLifecycleState.detached:
            widget.myUserRepo.setInactiveCustomer();
            break;
        }
      }
    
      @override
      Widget build(BuildContext context) {
        return widget.child;
      }
    
      @override
      void dispose() {
        widget.myUserRepo.setInactiveCustomer();
        WidgetsBinding.instance!.removeObserver(this);
        super.dispose();
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-11-23
      • 2020-06-19
      • 2019-06-19
      • 2011-03-04
      • 1970-01-01
      • 1970-01-01
      • 2019-04-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多