How to implement the QR code Scanner in a flutter

In this guide, we will learn how to implement the QR code Scanner by using the external package name qr_code_scanner in a flutter. A QR code scanner that works on both iOS and Android by natively embedding the platform view within Flutter. The integration with Flutter is seamless, much better than jumping into a native Activity or a ViewController to perform the scan. When a QR code is recognized, the text identified will be set in the ‘result’ of the type Barcode, which contains the output text as property ‘code’ of type String and scanned code type as property ‘format’ which is an enum BarcodeFormat, defined in the library.

As technology improves QR becomes more and more important in our life. QR code is widely used by the payment gateway and in many other services because they can store text, URL, email address, ph. numbers or any other form of data. Nowadays QR code scanning can be done very easily through mobile phones, they do not require special devices for scanning. This article will show how to create, scan, and save the QR to the user’s phone.

Key Features of QR Code

  • Safe and secure, it can be only read by machines.
  • They can store any type of data easily.
  • Quick the give response.
  • Easy to generate and scan.

To set up the qr_code_scanner in our application. At first, we should do the following things.

Step1: Add the dependency

Start by adding the dependency to the pubspec.yml file

dependencies:
   qr_code_scanner: ^0.7.0

or

We can do that by running the following command in our terminal: $ flutter pub add qr_code_scanner

Configuration: if we are using the latest version of the qr_code_scanner we must follow some of the guidance regarding the setting of our device

iOS

In order to use this plugin, add the following to your Info.plist file:

<key>io.flutter.embedded_views_preview</key>
<true/>
<key>NSCameraUsageDescription</key>
<string>This app needs camera access to scan QR codes</string>

 Android

In order to use this plugin, please update the Gradle, Kotlin, and Kotlin Gradle Plugin:

In android/build.gradle change ext.kotlin_version = '1.3.50' to ext.kotlin_version = '1.5.10'

In android/build.gradle change classpath 'com.android.tools.build:gradle:3.5.0' to classpath 'com.android.tools.build:gradle:4.2.0'

In android/gradle/wrapper/gradle-wrapper.properties change distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.2-all.zip to distributionUrl=https\://services.gradle.org/distributions/gradle-6.9-all.zip

In android/app/build.gradle change defaultConfig{ ... minSdkVersion 16 } to defaultConfig{ ... minSdkVersion 20 }

Warning 

If you are using Flutter Beta or Dev channel (1.25 or 1.26) you can get the following error:

java.lang.AbstractMethodError: abstract method "void io.flutter.plugin.platform.PlatformView.onFlutterViewAttached(android.view.View)"

This is a bug in Flutter which is being tracked here: https://github.com/flutter/flutter/issues/72185

There is a workaround by adding android.enableDexingArtifactTransform=false to your gradle.properties file.

Let’s take an example of how we can implement the QR code Scanner in our flutter application.

import 'package:flutter/material.dart';
import 'package:qr_code_scanner/qr_code_scanner.dart';

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

  @override
  State<QrCodeScreen> createState() => _QrCodeScreenState();
}

class _QrCodeScreenState extends State<QrCodeScreen> {
  final GlobalKey _gLobalkey = GlobalKey();
  QRViewController? controller;
  Barcode? result;
  void qr(QRViewController controller) {
    this.controller = controller;
    controller.scannedDataStream.listen((event) {
      setState(() {
        result = event;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Qr code Scanner'),
        centerTitle: true,
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            SizedBox(
              height: 400,
              width: 400,
              child: QRView(key: _gLobalkey, onQRViewCreated: qr),
            ),
            Padding(
              padding: const EdgeInsets.only(top: 15.0),
              child: Center(
                child: result != null
                    ? Text('${result!.code}')
                    : const Text('Scan a code again'),
              ),
            )
          ],
        ),
      ),
    );
  }
}

Meanwhile, when we run this application in the emulator or device, we should get the UI similar to the screenshot below:

Thank you for reading the Guide about How to implement the QR code Scanner in Flutter.