How do I logout a user from Firebase when closing the app in Flutter
340
Use WidgetsBindingObserver to do your stuff. Wrap the MaterialApp with AppLifeCycleManager()
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();
}
}
Author by
Henrique Tavolaro
Updated on January 02, 2023Comments
-
Henrique Tavolaro over 1 year
I have an app that can't persist the user state of firebase auth for security reasons but I can't find a way to logout the user when the app is closed or force closed.
I'm using a listener to navigate the user to next page but, with this, when I open the app it automatically navigate to the logged page.
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; }