How to stop the barcode scanner camera and pass the barcode value to TextFormField in Flutter?

Viewed 55

I'm using qr_code_scanner: ^1.0.1 for IOS app in Flutter, where in the app there is a form containing the product's information: barcode number, name, brand, etc... and what I did is when the user clicks on the barcode icon on TextFormField its moves to the scanner to scan the barcode. But I'm stuck in the next step where I want to stop the scanner (camera) and then pass the barcode number to the TextFormField like (auto filing) and finally return to the form to complete the product information.

NOTE: my code is exactly as the example in qr_code_scanner: ^1.0.1 so what should I change/add to get the desire result?

here is the part of the code

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Colors.white24,
        body: Column(children: <Widget>[
          Expanded(flex: 4, child: _buildQrView(context)),
          Expanded(
              flex: 1,
              child: Column(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: <Widget>[
                      if (result != null)
                        Text('${result!.code}') // رقم الباركود من الكاميرا
                      else
                      const Center(
                          child: Text(
                              'قم بمسح الرمز الشريطي للمنتج لإضافته إلى المخزون',
                              textAlign: TextAlign.center,
                              style: TextStyle(fontSize: 19)))
                  ]))
        ]));
  }

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

  void _onPermissionSet(BuildContext context, QRViewController ctrl, bool p) {
    log('${DateTime.now().toIso8601String()}_onPermissionSet $p');
    if (!p) {
      ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('لا يوجد سماح من الكاميرا')));
    }
  }

  @override
  void dispose() {
    controller?.dispose();
    super.dispose();
  }
}
1 Answers

In the void _onQrViewCreated you can navigate back to the page with the text input field instead of passing the scannedData to the result.

So you can do

controller.scannedDataStream.listen((scanData) {
   Navigator.of(context).push(
       MaterialPageRoute(
           builder: (context) => /*Widget with your text field*/(
               data: scanData.code,
           ),
       ),
   ); 
});

instead of

controller.scannedDataStream.listen((scanData) {
    setState(() {
        result = scanData;
    });
});
Related