diff --git a/lib/status_page.dart b/lib/status_page.dart index 2bb3d1e..bc0c74c 100644 --- a/lib/status_page.dart +++ b/lib/status_page.dart @@ -17,12 +17,8 @@ class StatusPage extends StatefulWidget { StatusPageState createState() => StatusPageState(); } -class StatusPageState extends State { - final WebSocketChannel channel = WebSocketChannel.connect( - Uri.parse('wss://api.pogdark.com:8889/ws'), - //Uri.parse('ws://localhost:8080/ws'), - ); - +class StatusPageState extends State with WidgetsBindingObserver { + WebSocketChannel? channel; late final Stream broadcastStream; late StreamController controller; List> messages = []; @@ -31,9 +27,42 @@ class StatusPageState extends State { @override void initState() { super.initState(); + WidgetsBinding.instance.addObserver(this); + _initializeWebSocket(); + } + + void _initializeWebSocket() { + channel = WebSocketChannel.connect( + Uri.parse('wss://api.pogdark.com:8889/ws'), + //Uri.parse('ws://localhost:8080/ws'), + ); + controller = StreamController.broadcast(); - controller.addStream(channel.stream); - broadcastStream = channel.stream.asBroadcastStream(); + controller.addStream(channel!.stream); + broadcastStream = channel!.stream.asBroadcastStream(); + } + + @override + void dispose() { + WidgetsBinding.instance.removeObserver(this); + channel?.sink.close(); + controller.close(); + super.dispose(); + } + + @override + void didChangeAppLifecycleState(AppLifecycleState state) { + if (state == AppLifecycleState.resumed) { + // Reestablish the WebSocket connection when the app returns to the foreground + _reconnectWebSocket(); + } + } + + void _reconnectWebSocket() { + if (channel != null) { + channel!.sink.close(); + } + _initializeWebSocket(); } List> _getMessagesByStatus(String status) { @@ -58,7 +87,7 @@ class StatusPageState extends State { 'Status': newStatus.isEmpty ? 'expired' : newStatus, 'Timestamp': DateTime.now().toIso8601String(), }); - channel.sink.add(message); + channel!.sink.add(message); if (mounted) { Fluttertoast.showToast( @@ -277,11 +306,4 @@ class StatusPageState extends State { ), ); } - - @override - void dispose() { - channel.sink.close(); - controller.close(); - super.dispose(); - } }