Simplify Barcode and QR code Scan in Flutter apps
Ever came across a scenario where you wanted your Flutter app to scan QR codes and Barcodes? In this article, I will walk you through the steps required to scan and read QR codes and Barcodes in Flutter app with the help of an example.
In the example, we are going to build a simple UI that scans Barcodes and QR codes and records the value in a TextField
box. We can then store this value and use anywhere in the program.
- We will begin by importing the qr_code_scanner package in a newly created Flutter project.
Run the following command in the terminal to make sure that the latest version of the package is imported:
$ flutter pub add qr_code_scanner
This package scans both QR codes and barcodes.
2. Since the package uses camera to scan the codes, follow the documentation to make some platform specific changes(updating gradle
and minSdkVersion
on Android and addingNSCameraUsageDescription
in Info.plist file)
3. Once step 1 & 2 are complete, we can now start with the QR code.
If the camera permission is allowed, the camera will start scanning for the codes. Once the code is scanned, the camera will be paused and the code will be recorded for future use as shown below.
The code can be stored in a TextField
using a TextEditingController
which can also be edited(manually entered by user) in case the camera could not capture a damaged QR/Barcode. We will also allow the user to toggle flash option of Camera.
TextEditingController scannedCode = TextEditingController(text: ‘QR Code’);
4. In case you want to rescan the code or if by any chance the barcode was incorrectly read(very rare), we will add a button to rescan the QR/barcode. This will resume the camera to record the barcode again and also replace the TextEditingController
value and the process repeats.
We will also use a QRViewController
to read the incoming barcode data stream.
QRViewController? controller;
5. buildQrView
is a widget that passes the current context to build a QR view in the UI. You can set the height and width of the QRView
window here as per the device dimensions.
This widget also confirms if the camera permission is set or not. You can display a custom message in case the permission was denied.
6. The QRView
has a parameter onQRViewCreated
that runs a function when the QRView
is created. This function uses the QRController
to start scanning the incoming camera data, in streams. When an object of type Barcode
is detected, the scanned code from this object is then assigned to the TextEditingController
.
7. Lastly, don’t forget to dispose
the controllers to avoid memory leak.
controller?.dispose();
scannedCode.dispose();