import 'package:flutter/material.dart'; import 'package:universal_html/html.dart' as html; import '../service/token_storage_service.dart'; import '../service/api_service.dart'; class SecurePopScope extends StatefulWidget { final Widget child; const SecurePopScope({Key? key, required this.child}) : super(key: key); @override State createState() => _SecurePopScopeState(); } class _SecurePopScopeState extends State { final TokenStorageService _tokenService = TokenStorageService(); late ApiService _apiService; @override void initState() { super.initState(); _apiService = ApiService(context); // 🔥 Push dummy state (IMPORTANT for Firefox) html.window.history.pushState(null, '', html.window.location.href); html.window.onPopState.listen((event) async { await _handleBack(); }); } Future _handleBack() async { final token = await _tokenService.getCurrentToken(); // If no token → force login if (token == null || token.isEmpty) { _redirectToLogin(); return; } final shouldLogout = await _showLogoutDialog(); if (shouldLogout) { await _tokenService.clearAll(); await _apiService.logout(); _redirectToLogin(); } else { // 🔥 Re-push state (VERY IMPORTANT for Firefox) html.window.history.pushState(null, '', html.window.location.href); } } void _redirectToLogin() { if (!mounted) return; Navigator.pushNamedAndRemoveUntil( context, 'hrLogin', (route) => false, ); } Future _showLogoutDialog() async { return await showDialog( context: context, barrierDismissible: false, builder: (context) => AlertDialog( title: const Text("Confirm Logout"), content: const Text("Do you want to logout?"), actions: [ TextButton( onPressed: () => Navigator.pop(context, false), child: const Text("Cancel"), ), TextButton( onPressed: () => Navigator.pop(context, true), child: const Text("Logout"), ), ], ), ) ?? false; } @override Widget build(BuildContext context) { return widget.child; // ❌ Don't rely on PopScope for web } }