From 16d1145efdaecc411ab03fc09a015d285de232c2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lukas=20M=C3=BCllner?= Date: Mon, 23 Feb 2026 08:53:04 +0100 Subject: [PATCH] fix: convert HomeScreen to StatefulWidget with mounted checks Prevents Duplicate GlobalKeys / wrong build scope crashes when opening dialogs from async scanner and DB operations. The scan button is also disabled while a query is in flight to prevent double-taps. --- lib/main.dart | 40 +++++++++++++++++++++++----------------- 1 file changed, 23 insertions(+), 17 deletions(-) diff --git a/lib/main.dart b/lib/main.dart index 76d3bea..2a28b2e 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -339,9 +339,16 @@ class _LoginScreenState extends State { } // ── Home Screen ─────────────────────────────────────────────────────── -class HomeScreen extends StatelessWidget { +class HomeScreen extends StatefulWidget { const HomeScreen({super.key}); + @override + State createState() => _HomeScreenState(); +} + +class _HomeScreenState extends State { + bool _isBusy = false; + @override Widget build(BuildContext context) { final user = supabase.auth.currentUser; @@ -379,18 +386,20 @@ class HomeScreen extends StatelessWidget { floatingActionButton: FloatingActionButton.extended( icon: const Icon(Icons.camera_alt), label: const Text('Scan'), - onPressed: () => _openScanner(context), + onPressed: _isBusy ? null : _openScanner, ), ); } /// Opens the scanner, gets the hw_id, then queries the DB. - Future _openScanner(BuildContext context) async { + Future _openScanner() async { final hwId = await Navigator.of(context).push( MaterialPageRoute(builder: (_) => const ScannerScreen()), ); - if (hwId == null || !context.mounted) return; + if (hwId == null || !mounted) return; + + setState(() => _isBusy = true); try { final data = await supabase @@ -399,21 +408,18 @@ class HomeScreen extends StatelessWidget { .eq('hw_id', hwId) .maybeSingle(); - if (!context.mounted) return; + if (!mounted) return; + setState(() => _isBusy = false); - if (data != null) { - showDialog( - context: context, - builder: (_) => _AlreadyExistsDialog(hwId: hwId), - ); - } else { - showDialog( - context: context, - builder: (_) => _AddCarDialog(hwId: hwId), - ); - } + await showDialog( + context: context, + builder: (_) => data != null + ? _AlreadyExistsDialog(hwId: hwId) + : _AddCarDialog(hwId: hwId), + ); } catch (e) { - if (!context.mounted) return; + if (!mounted) return; + setState(() => _isBusy = false); ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text('DB error: $e'), backgroundColor: Colors.red), );