juliansteenbakker / mobile_scanner

A universal scanner for Flutter based on MLKit. Uses CameraX on Android and AVFoundation on iOS.
BSD 3-Clause "New" or "Revised" License
877 stars 509 forks source link

[Android] mobile scanner preview randomly blank when navigating to scanner widget #1135

Open windrexcz opened 2 months ago

windrexcz commented 2 months ago

Hello, iam working on a scanner application and i may have found a bug with camera preview display logic.

ezgif-2-2877c977bd

In this GIF i attached at end I repeatedly navigate back and forth from main menu back to scanning window until error occurs (the scanning window being blank).

(The layout change where it goes from 50/50 blank -> 0/100 barcode list -> 50/50 error icon is done by me with gesture that cannot be seen in the gif)

Most of the times the camera opens without issue, but sometimes the preview is blank. However in the blank state, it still detects barcodes that are placed in front of the camera.

Sometimes the error occurs even after some longer duration (for example being in main menu for one minute and then going to scan widget), like there were some unreleased resources even though iam not scanning anymore.

I have placed a debug line in the mobile scanner file to try diagnose the issue, but when it occurs the error print does not trigger

        if (error != null) {
          const Widget defaultError = ColoredBox(
            color: Colors.black,
            child: Center(child: Icon(Icons.error, color: Colors.white)),
          );

          print('⚓♦️♦️⚓ MobileScanner: error: $error'); <--------------------------------------------

          return widget.errorBuilder?.call(context, error, child) ??
              defaultError;
        }

This is my init state code

  @override
  void initState() {
    WidgetsBinding.instance.addObserver(this);
    unawaited(cameraController.start());

    _barcodeSubscription = cameraController.barcodes.listen((barcodes) {
      debugPrintCHD("Barcode detected: $barcodes");
      _handleBarcodeDetection(barcodes: barcodes, manualBarcode: null);
    });
    super.initState();
  }

And this is my widget observer code copied from example code

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (!cameraController.value.isInitialized) {
      return;
    }

    switch (state) {
      case AppLifecycleState.detached:
      case AppLifecycleState.hidden:
      case AppLifecycleState.paused:
        return;
      case AppLifecycleState.resumed:
        // Restart the scanner when the app is resumed.
        // Don't forget to resume listening to the barcode events.
        _barcodeSubscription = cameraController.barcodes.listen((barcodes) {
          debugPrintCHD("Barcode detected: $barcodes");
          _handleBarcodeDetection(barcodes: barcodes, manualBarcode: null);
        });
        unawaited(cameraController.start());
      case AppLifecycleState.inactive:
        // Stop the scanner when the app is paused.
        // Also stop the barcode events subscription.
        unawaited(_barcodeSubscription?.cancel());
        _barcodeSubscription = null;
        unawaited(cameraController.stop());
    }
  }

I have also tried resolving this issue by forcing camera dispose on pop like so: (didnt help though)

  @override
  Widget build(BuildContext context) {
    return PopScope(
      onPopInvoked: (_) async {
        if (cameraController.value.isInitialized || cameraController.value.isRunning) {
          cameraController.stop();
          await cameraController.dispose();
        }
      },
      child: Scaffold(
      ........

I don't have idea what could i be doing wrong, so iam creating this 'ticket'.

Any help would be appriciated, and sorry for my bad grammar

Flutter doctor -v: [√] Flutter (Channel stable, 3.22.2, on Microsoft Windows [Version 10.0.22631.3880], locale cs-CZ) [√] Windows Version (Installed version of Windows is version 10 or higher) [√] Android toolchain - develop for Android devices (Android SDK version 34.0.0) [X] Chrome - develop for the web (Cannot find Chrome executable at .\Google\Chrome\Application\chrome.exe) ! Cannot find Chrome. Try setting CHROME_EXECUTABLE to a Chrome executable. [√] Visual Studio - develop Windows apps (Visual Studio Community 2022 17.9.7) [!] Android Studio (version 2023.2) X Unable to find bundled Java version. [√] Android Studio (version 2024.1) [√] VS Code (version 1.91.1) [√] Connected device (3 available) [√] Network resources

! Doctor found issues in 2 categories. PS C:\Users\avetr\AndroidStudioProjects\chydis_skener_flutter> flutter doctor -v [√] Flutter (Channel stable, 3.22.2, on Microsoft Windows [Version 10.0.22631.3880], locale cs-CZ) • Flutter version 3.22.2 on channel stable at C:\flutterDev\flutter • Upstream repository https://github.com/flutter/flutter.git • Framework revision 761747bfc5 (8 weeks ago), 2024-06-05 22:15:13 +0200 • Engine revision edd8546116 • Dart version 3.4.3 • DevTools version 2.34.3

[√] Windows Version (Installed version of Windows is version 10 or higher)

[√] Android toolchain - develop for Android devices (Android SDK version 34.0.0) • Android SDK at C:\Users\avetr\AppData\Local\Android\sdk • Platform android-34, build-tools 34.0.0 • Java binary at: C:\Program Files\Android\Android Studio1\jbr\bin\java • Java version OpenJDK Runtime Environment (build 17.0.11+0--11852314) • All Android licenses accepted.

[X] Chrome - develop for the web (Cannot find Chrome executable at .\Google\Chrome\Application\chrome.exe) ! Cannot find Chrome. Try setting CHROME_EXECUTABLE to a Chrome executable.

[√] Visual Studio - develop Windows apps (Visual Studio Community 2022 17.9.7) • Visual Studio at C:\Program Files\Microsoft Visual Studio\2022\Community • Visual Studio Community 2022 version 17.9.34902.65 • Windows 10 SDK version 10.0.22621.0

[!] Android Studio (version 2023.2) • Android Studio at C:\Program Files\Android\Android Studio • Flutter plugin can be installed from: https://plugins.jetbrains.com/plugin/9212-flutter • Dart plugin can be installed from: https://plugins.jetbrains.com/plugin/6351-dart X Unable to find bundled Java version. • Try updating or re-installing Android Studio.

[√] Android Studio (version 2024.1) • Android Studio at C:\Program Files\Android\Android Studio1 • Flutter plugin can be installed from: https://plugins.jetbrains.com/plugin/9212-flutter • Dart plugin can be installed from: https://plugins.jetbrains.com/plugin/6351-dart • Java version OpenJDK Runtime Environment (build 17.0.11+0--11852314)

[√] VS Code (version 1.91.1) • VS Code at C:\Users\avetr\AppData\Local\Programs\Microsoft VS Code • Flutter extension can be installed from: https://marketplace.visualstudio.com/items?itemName=Dart-Code.flutter

[√] Connected device (3 available) • 22031116BG (mobile) • SWORVKUKUW4DFUX8 • android-arm64 • Android 11 (API 30) • Windows (desktop) • windows • windows-x64 • Microsoft Windows [Version 10.0.22631.3880] • Edge (web) • edge • web-javascript • Microsoft Edge 127.0.2651.74

[√] Network resources • All expected network resources are available.

Shakle commented 2 months ago

I have similar problem, but it's blinking when keyboard is shown and then only scanner restart helps.

sagarehs commented 2 months ago

I have similar problem, tested with 5.2.0

Currently i have added batch isbn scan option, It working fine if we scan all different books isbn but in case user scan same isbn multiple time it display black screen with error icon

https://github.com/user-attachments/assets/29f50022-6e77-43bd-ae1e-2ac90f123b72

ragummrsa2930 commented 2 months ago

@override void dispose() { scannerController.dispose(); super.dispose(); }

Try to add a controller dispos() option in the dispose method. Looks like it is working for me. I will check with some more devices.

sagarehs commented 2 months ago

@OverRide void dispose() { scannerController.dispose(); super.dispose(); }

Try to add a controller dispos() option in the dispose method. Looks like it is working for me. I will check with some more devices.

@ragummrsa2930 Thank you for your response. However, I have multiple scan options on the same screen. I tried stopping and starting the scan again in the onDetect method. This approach works sometimes but not always. I’ve already shared a video in this comment If we use dispose in onDetect, it displays a white screen.

MrLiuYunPing commented 4 weeks ago

generic error sometimes, I can only kill the app to fix.

dreamo101 commented 1 week ago

I repeatedly navigate back and forth from the main menu to the scanning window until an error occurs (the scanning window appears blank).

and I tried printing the error, but I couldn't see any issues, yet the scanning window appears blank.

The case where the scanning window appears blank occurs when I press back from the scan page to the home page and then go back quickly to the scan page again.

So I used a delay to fix the problem for now like this:

await Future.delayed(const Duration(milliseconds: 200)); Navigator.push( context, MaterialPageRoute( builder: (context) => const MobileQrCodeScannerScreen(), ),

I tried milliseconds: 200 and there was no problem with the scanning window appearing blank, but if I use 100, it causes issues.

arnabonetraker commented 2 days ago

Its quite similar to my case, where the preview went empty and stayed like this. But actual scanning was working, only the preview had issue.

1119