Barcode / QR Code Scanner in Flutter

The majority of applications use Barcodes and QR codes for scanning product data, transferring cash to somebody, keeping the info in QR code format so on. we will store text, SMS, URLs, phone contacts, photos, and a lot of other formats in QR codes

In this tutorial, we’ll look at how to implement a barcode / QR code scanner in Flutter. We have a package named flutter_barcode_scanner out there in pub.dev to achieve this functionality.

In order to achieve functionality, we have two important methods in this package.

  1. scanBarcode(..)
  2. getBarcodeStreamReceiver(..)
 static Future scanBarcode(String lineColor, String cancelButtonText,
      bool isShowFlashIcon, ScanMode scanMode)

The camera is used to scan the barcode / QR code till it is identified. It will return the result as String.

  • String lineColor: This property allows us to provide a colour to a scan line within a scan window.
  • String cancelButtonText: This property allows us to specify a string to cancel an action.
  • bool isShowFlashIcon: If it is the true, the Flas icon will appear on the screen, otherwise not.
  • ScanMode scnMode: We can use this property to control the scan mode. [QR, BARCODE, DEFAULT] mods are available here.
Stream? getBarcodeStreamReceiver(String lineColor,
      String cancelButtonText, bool isShowFlashIcon, ScanMode scanMode)

It will return the continuous stream of barcode scans until the user cancels the operation. Returns a stream of barcode strings that were identified.

  • String lineColor: This property allows us to provide a colour to a scan line within a scan window.
  • String cancelButtonText: This property allows us to specify a string to cancel an action.
  • bool isShowFlashIcon: If it is the true, the Flas icon will appear on the screen, otherwise not.
  • ScanMode scnMode: We can use this property to control the scan mode. [QR, BARCODE, DEFAULT] mods are available here.

Basic implementaion of Barcode / QR Code Scanner

1. Add a new flutter project in your favorite IDE, and take away the boilerplate code. Ref link. Ref link
2. Add the flutter_barcode_scanner dependency in pubspec.yaml file, and install it by running pub get.

dependencies:
  flutter:
    sdk: flutter
  flutter_barcode_scanner: < "Latest version ">

3. Add the following code into the main.dart file

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_barcode_scanner/flutter_barcode_scanner.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State {
  String _scanBarcode = 'Unknown';

  @override
  void initState() {
    super.initState();
  }

  Future startBarcodeScanStream() async {
    FlutterBarcodeScanner.getBarcodeStreamReceiver(
            '#ff6666', 'Cancel', true, ScanMode.BARCODE)!
        .listen((barcode) => print(barcode));
  }

  Future scanQR() async {
    String barcodeScanRes;
    try {
      barcodeScanRes = await FlutterBarcodeScanner.scanBarcode(
          '#ff6666', 'Cancel', true, ScanMode.QR);
      print(barcodeScanRes);
    } on PlatformException {
      barcodeScanRes = 'Failed to get platform version.';
    }

    setState(() {
      _scanBarcode = barcodeScanRes;
    });
  }

  Future scanBarcodeNormal() async {
    String barcodeScanRes;
    try {
      barcodeScanRes = await FlutterBarcodeScanner.scanBarcode(
          '#ff6666', 'Cancel', true, ScanMode.BARCODE);
      print(barcodeScanRes);
    } on PlatformException {
      barcodeScanRes = 'Failed to get platform version.';
    }

    if (!mounted) return;
    setState(() {
      _scanBarcode = barcodeScanRes;
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        debugShowCheckedModeBanner: false,
        home: Scaffold(
            appBar: AppBar(title: const Text('Barcode Scanner')),
            body: Builder(builder: (BuildContext context) {
              return Container(
                  alignment: Alignment.center,
                  child: Flex(
                      direction: Axis.vertical,
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        ElevatedButton(
                            onPressed: () => scanBarcodeNormal(),
                            child: const Text('Barcode scan')),
                        ElevatedButton(
                            onPressed: () => scanQR(),
                            child: const Text('QR scan')),
                        ElevatedButton(
                            onPressed: () => startBarcodeScanStream(),
                            child: const Text('Barcode scan stream')),
                        Text('Scan result : $_scanBarcode\n',
                            style: const TextStyle(fontSize: 20))
                      ]));
            })));
  }
}

4.  let’s run the application and see the output

For more details please visit pub.dev

Thanks for reading .. 🙂

Leave a Comment