FLUTTER / How to scan barcodes with RawKeyboardListener?

548 views Asked by At

I'm building a barcode reader application. Barcode will happen with barcode reading included in an android device. I'm trying this with RawKeyboardListener, but I don't know how to get the barcode result, can you help?

 RawKeyboardListener(
                      onKey: handleKey,
                      focusNode: FocusNode(),
                      autofocus: true,
                      child: Text('No textfield'),
                    ),


  handleKey(RawKeyEvent key) {
    
  }
1

There are 1 answers

0
Nahiyan Basmeh On

The onKey() function in the RawKeyboardListener() returns an event which has RawKeyDownEvent and RawKeyUpEvent. An event returns a single character in such format -

RawKeyDownEvent#1640d(logicalKey: LogicalKeyboardKey#00061(keyId: "0x00000061", keyLabel: "A", debugName: "Key A"), physicalKey: PhysicalKeyboardKey#70004(usbHidUsage: "0x00070004", debugName: "Key A"), repeat: false)

So if the barcode returns a Name, you can retrieve by using this code:

String qrCodeText = '';
RawKeyboardListener(
    autofocus: true,
    focusNode: FocusNode(),
    onKey: (event) {
      if (event is RawKeyDownEvent) {
        if (event.logicalKey.keyLabel.length == 1) {
          qrCodeText += event.logicalKey.keyLabel;
        } else if (event.logicalKey.keyLabel == 'Enter') {
          print('Data received from the QR Code: $qrCodeText');
        }
      }
    },
    child: Text('$qrCodeText'));

Hope this solves your problem!