From 2872265f237afac12a22927d4d122684e1fe0783 Mon Sep 17 00:00:00 2001 From: Elias Andualem Date: Fri, 18 Feb 2022 18:57:37 +0300 Subject: [PATCH] fix: Handle all cases when a controller should be initialized and disposed --- lib/src/mobile_scanner.dart | 34 +++++++++++++++++++++++++--------- 1 file changed, 25 insertions(+), 9 deletions(-) diff --git a/lib/src/mobile_scanner.dart b/lib/src/mobile_scanner.dart index b880e9dab..ad18863e8 100644 --- a/lib/src/mobile_scanner.dart +++ b/lib/src/mobile_scanner.dart @@ -26,9 +26,12 @@ class MobileScanner extends StatefulWidget { final BoxFit fit; /// Create a [MobileScanner] with a [controller], the [controller] must has been initialized. - const MobileScanner( - {Key? key, this.onDetect, this.controller, this.fit = BoxFit.cover}) - : assert((controller != null)), + const MobileScanner({ + Key? key, + this.onDetect, + this.controller, + this.fit = BoxFit.cover, + }) : assert((controller != null)), super(key: key); @override @@ -43,11 +46,7 @@ class _MobileScannerState extends State @override void initState() { super.initState(); - if (widget.controller == null) { - controller = MobileScannerController(); - } else { - controller = widget.controller!; - } + controller = widget.controller ?? MobileScannerController(); } @override @@ -96,9 +95,26 @@ class _MobileScannerState extends State }); } + @override + void didUpdateWidget(covariant MobileScanner oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.controller == null) { + if (widget.controller != null) { + controller.dispose(); + controller = widget.controller!; + } + } else { + if (widget.controller == null) { + controller = MobileScannerController(); + } else if (oldWidget.controller != widget.controller) { + controller = widget.controller!; + } + } + } + @override void dispose() { - controller.dispose(); + if (widget.controller == null) controller.dispose(); super.dispose(); } }