Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter qr_code_scanner showing black screen instead of the scanner

I am using qr_code_scanner to scan a qr code in flutter . The point here is that it shows a black screen instead of showing a scanner . I cant seem to start the qr reader . but suppose i exit the app like put the app in the background and then come to the app again the camera suddenly started . Cant seem to find why the camera dosent start on the app start .


class Home extends StatefulWidget {
  const Home({Key? key}) : super(key: key);

  @override
  State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: QrScan(),
    );
  }
}

class QrScan extends StatefulWidget {
  const QrScan({Key? key}) : super(key: key);

  @override
  State<QrScan> createState() => _QrScanState();
}

class _QrScanState extends State<QrScan> {
  final GlobalKey qrKey = GlobalKey(debugLabel: 'QR');
  Barcode? result;
  QRViewController? controller;

  @override
  void initState() {
    super.initState();
    controller?.resumeCamera();
  }

  // In order to get hot reload to work we need to pause the camera if the platform
  // is android, or resume the camera if the platform is iOS.
  @override
  void reassemble() {
    super.reassemble();
    if (Platform.isAndroid) {
      controller?.pauseCamera();
    } else if (Platform.isIOS) {
      controller?.resumeCamera();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: <Widget>[
          Expanded(
            flex: 5,
            child: QRView(
              key: qrKey,
              onQRViewCreated: _onQRViewCreated,
              overlay: QrScannerOverlayShape(
                  borderRadius: 10, borderWidth: 5, borderColor: Colors.white),
            ),
          ),
          Expanded(
            flex: 1,
            child: Center(
              child: (result != null)
                  ? Text(
                      'Barcode Type: ${describeEnum(result!.format)}   Data: ${result?.code}')
                  : Text('Scan a code'),
            ),
          )
        ],
      ),
    );
  }

  void _onQRViewCreated(QRViewController controller) {
    this.controller = controller;
    controller.scannedDataStream.listen((scanData) {
      setState(() {
        result = scanData;
      });
    });
  }

  @override
  void dispose() {
    controller?.dispose();
    super.dispose();
  }
}
like image 662
Sovit Nayak Avatar asked Sep 06 '25 03:09

Sovit Nayak


2 Answers

Try to pause and resume the camera inside your _onQRViewCreated:

void _onQRViewCreated(QRViewController controller) {
    this.controller = controller;
    controller.scannedDataStream.listen((scanData) {
      setState(() {
        result = scanData;
      });
    });
    controller.pauseCamera();
    controller.resumeCamera();
  }
like image 119
Ozan Taskiran Avatar answered Sep 07 '25 19:09

Ozan Taskiran


Try this it will surely solve the problem!

 @override
      Widget build(BuildContext context) {
        if (controller != null && mounted) {
          controller!.pauseCamera();
          controller!.resumeCamera();
        }

Use the below code if you are using the flashlight feature!

class QRScanner extends StatefulWidget {
  const QRScanner({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() => _QRScannerState();
}

class _QRScannerState extends State<QRScanner> {
  Barcode? result;
  QRViewController? controller;
  final GlobalKey qrKey = GlobalKey(debugLabel: 'QR');
  bool isflash = false;
  // In order to get hot reload to work we need to pause the camera if the platform
  // is android, or resume the camera if the platform is iOS.
  @override
  void reassemble() {
    super.reassemble();
    if (Platform.isAndroid) {
      controller!.pauseCamera();
      controller!.resumeCamera();
    }
    controller!.resumeCamera();
  }

  @override
  Widget build(BuildContext context) {
    if (controller != null && mounted && !isflash) {
      controller!.pauseCamera();
      controller!.resumeCamera();
    }

    return Scaffold(
      appBar:
          appBar(context, backbutton: true, icon: true, notifications: true),
      body: Stack(
        children: <Widget>[
          _buildQrView(context),
          Column(
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              // if (result != null)
              //   Text(
              //     'Barcode Type: ${describeEnum(result!.format)}   Data: ${result!.code}',
              //     style: const TextStyle(color: Colors.white),
              //   )
              // else
              //   const Text('Scan a code'),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  GestureDetector(
                    onTap: () async {
                      isflash = !isflash;
                      await controller?.toggleFlash();
                      setState(() {});
                    },
                    child: Container(
                      margin: const EdgeInsets.all(8),
                      child: FutureBuilder(
                        future: controller?.getFlashStatus(),
                        builder: (context, snapshot) {
                          return snapshot.data == false
                              ? const Icon(
                                  Icons.flash_off,
                                  color: Colors.white,
                                )
                              : const Icon(Icons.flash_on, color: Colors.white);
                        },
                      ),
                    ),
                  ),
                  GestureDetector(
                    onTap: () async {
                      await controller?.flipCamera();
                      setState(() {});
                    },
                    child: Container(
                      margin: const EdgeInsets.all(8),
                      child: FutureBuilder(
                        future: controller?.getCameraInfo(),
                        builder: (context, snapshot) {
                          if (snapshot.data != null) {
                            return const Icon(Icons.cameraswitch_rounded,
                                color: Colors.white);
                          } else {
                            return const SizedBox();
                          }
                        },
                      ),
                    ),
                  )
                ],
              ),
            ],
          )
        ],
      ),
    );
  }

  Widget _buildQrView(BuildContext context) {
    var scanArea = (Get.width < 400 || Get.height < 400) ? 230.0 : 330.0;
    return QRView(
      key: qrKey,
      onQRViewCreated: _onQRViewCreated,
      overlay: QrScannerOverlayShape(
          borderColor: buttonColor,
          borderRadius: 2,
          borderLength: 35,
          borderWidth: 6,
          cutOutSize: scanArea),
      onPermissionSet: (ctrl, p) => _onPermissionSet(context, ctrl, p),
    );
  }

  void _onQRViewCreated(QRViewController controller) {
    setState(() {
      this.controller = controller;
    });
    controller.scannedDataStream.listen((scanData) {
      if (scanData != null) {
        setState(() {
          result = scanData;
        });
        Get.find<QRService>().updateResult(scanData.code);
        // Get.defaultDialog(
        //   content: Text("${scanData.code}"),
        // );
        Get.back();
        // Get.offAll(() => const QRmainScreen());
      }
    });
  }

  void _onPermissionSet(BuildContext context, QRViewController ctrl, bool p) {
    log('${DateTime.now().toIso8601String()}_onPermissionSet $p');
    if (!p) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('no Permission')),
      );
    }
  }

  @override
  void dispose() {
    controller?.dispose();
    super.dispose();
  }
}
like image 37
Mashood .h Avatar answered Sep 07 '25 21:09

Mashood .h