androidflutterqr-codebarcodescanning

Using flutter how to get scan code from hand held device


How to get the scan code from hand held device while clicking the triger button in device and update the text in textfield controller.

I need to capture the scan code from hand held device which can scan the both QR and Bar code and update the textfield controller. Please Help


Solution

  • Finally, I have found the answer.

    Every handheld device scanner must have a scan tool or scan-related service tool (Software) that is built into the device. And must have the Barcode or QR code hardware within the device.

    Make sure the scanner service is started and running. This will be indicated in the handheld device.

    There are two different ways to handle this situation.

    Using Test Field we need to have the Focus node and Text Field Controller. Note: If the scan code contains multiple lines then we need to set Text Field max lines to 2 or more according to your liking. (maxLines: 2, This will have the scroll option if the lines gets more than two).

    Note: To listen using the Text Field's focus node make sure that the text field has focus.

    Add this to the same class

    TextEditingController scanCtrl = TextEditingController();
    FocusNode focusNode = FocusNode();
    
      @override
      void initState() {
        focusNode.requestFocus();
        super.initState();
      }
    

    Use this code

    TextField(
       controller: scanCtrl,
       enabled: true,
       focusNode: focusNode, // To Lisern the scan code
       autofocus: true, // To have the focus at intital
       maxLines: 2,
       onChanged: (val) {
         debugPrint("Scan Value\n$val"); // To print the scan result
         FocusScope.of(context).requestFocus(focusNode); // To re-focus the text field
       },
       decoration: InputDecoration(
         contentPadding: const EdgeInsets.only(
             left: 18, right: 18, top: 10, bottom: 10),
         fillColor: Colors.white,
         filled: true,
         isDense: true,
         hintText:"Scan Code",
         enabledBorder: const OutlineInputBorder(
           borderRadius: BorderRadius.all(Radius.circular(8)),
           borderSide: BorderSide(color: Color(0xFFA2A2A2)),
         ),
         disabledBorder: const OutlineInputBorder(
           borderRadius: BorderRadius.all(Radius.circular(8)),
           borderSide: BorderSide(color: Color(0xFFA2A2A2)),
         ),
         border: const OutlineInputBorder(
           borderRadius: BorderRadius.all(Radius.circular(8)),
         ),
         focusedBorder: const OutlineInputBorder(
           borderRadius: BorderRadius.all(Radius.circular(8)),
           borderSide: BorderSide(color: Color(0xFFA2A2A2)),
         ),
       ),
     ),
    

    If you want to listen for barcode instead of using the Text Field then check the flutter_barcode_listener from Pub dev. Flutter Barcode Listener

    If you have any doubts ask them in comments.