import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import '../auth_provider.dart'; class LogoutScreen extends StatelessWidget { const LogoutScreen({super.key}); @override Widget build(BuildContext context) { final auth = Provider.of(context, listen: false); // Use addPostFrameCallback to ensure the dialog is shown after the widget // has been built, preventing errors like "setState() called during build". WidgetsBinding.instance.addPostFrameCallback((_) { // Check if a dialog is already open to prevent multiple dialogs // This is a simple check, more robust solutions might involve a state variable // if this screen could be rebuilt frequently without navigation. if (Navigator.of(context).canPop() && ModalRoute.of(context)?.isCurrent == true) { showDialog( context: context, barrierDismissible: false, // User must choose an action (Cancel/Logout) builder: (dialogContext) => AlertDialog( title: const Text("Are you sure?"), content: const Text("Do you really want to log out?"), actions: [ TextButton( onPressed: () { Navigator.pop(dialogContext); // Close dialog // Go back to the previous screen if user cancels logout Navigator.pop(context); }, child: const Text("Cancel"), ), ElevatedButton( onPressed: () { Navigator.pop(dialogContext); // Close dialog auth.logout(); // Navigate to login screen and remove all routes below it Navigator.pushNamedAndRemoveUntil(context, '/', (route) => false); }, style: ElevatedButton.styleFrom( backgroundColor: Colors.red[700], foregroundColor: Colors.white, ), child: const Text("Logout"), ), ], ), ); } }); // The LogoutScreen itself can be an empty Scaffold, as its primary // purpose is to trigger the dialog immediately upon navigation. return Scaffold( appBar: AppBar(title: const Text("Logout")), body: const Center( child: CircularProgressIndicator(), // Show a loading indicator briefly ), ); } }