Flutterexperts

Empowering Vision with FlutterExperts' Expertise
Scanning & Generating QR code in Flutter

Introduction

In this blog, we shall discuss how to generate and scan QR code in your Flutter app. 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.

Key Features of Bar code and QR code

  1. Safe and secure, they are only readable by machines.
  2. They can store any form of data easily
  3. Quick Response
  4. Data stored in static QR codes can not be edited.
  5. Easy to generate and scan

Table of content

  1. Installing Package
  2. Generate QR code
  3. Scan QR code
  4. GitHub Link

:: Installing Package

Update your pubspec.yaml file with the following package:

barcode_scan | Flutter Package
example/lib/main.dart import ‘dart:async’; import ‘dart:io’ show Platform; import…pub.dev

qr_flutter | Flutter Package
QR. Flutter is a Flutter library for simple and fast QR code rendering via a Widget or custom painter.pub.dev

dependencies:
barcode_scan:
qr_flutter:

:: Generate QR code

Import import ‘package:qr_flutter/qr_flutter.dart’;

Let’s build a text field to take input from the user:

Initialize a textEditingController for the field:

TextEditingController qrTextController = TextEditingController();

Create a text field with hint text:

TextField(
controller: qrTextController,
decoration: InputDecoration(
hintText: "please enter some data",
),
),

Code to design the text field:

Padding(
padding: const EdgeInsets.all(8.0),
child: Card(
elevation: 5,
child: ListTile(
leading: Icon(Icons.edit),
trailing: FlatButton(
child: Text(
"ENTER",
style: TextStyle(
color: Colors.white,
),
),
color: Colors.green,
onPressed: () {
},
),
title: TextField(
controller: qrTextController,
decoration: InputDecoration(
hintText: "please enter some data",
),
),
),
),
),

Submitting the text entered by the user to the QR code data:

onPressed: () {
setState(() {
dummyData = qrTextController.text == ""
? null
: qrTextController.text;
});
},

dummyData is a string that is the data for QR code. Here I have declared a condition to specify the dummyData , if the qrTextController is “” then it will be null otherwise qrTextController will be the data of the dummyData string.

Creating a QrImage

import 'package:qr_flutter/qr_flutter.dart'; package provides us QrImage() class to create a code image of the data given by the user.

QrImage(
data: dummyData,
),

Creating a QrImage with embeddedImage

QrImage(
embeddedImage: NetworkImage(
"https://avatars1.githubusercontent.com/u/41328571?s=280&v=4",
),
data: dummyData,
),

generate.dart

import 'package:flutter/material.dart';
import 'package:qr_flutter/qr_flutter.dart';
class GeneratePage extends StatefulWidget {
@override
State<StatefulWidget> createState() => GeneratePageState();
}
class GeneratePageState extends State<GeneratePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Generate QR code'),
),
body: ListView(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: Card(
elevation: 5,
child: ListTile(
leading: Icon(Icons.edit),
trailing: FlatButton(
child: Text(
"ENTER",
style: TextStyle(
color: Colors.white,
),
),
color: Colors.green,
onPressed: () {
setState(() {
dummyData = qrTextController.text == ""
? null
: qrTextController.text;
});
},
),
title: TextField(
controller: qrTextController,
decoration: InputDecoration(
hintText: "please enter some data",
),
),
),
),
),
(dummyData == null)
? Center(child: Text("enter some text to display qr code..."))
: QrImage(
embeddedImage: NetworkImage(
"https://avatars1.githubusercontent.com/u/41328571?s=280&v=4",
),
data: dummyData,
gapless: true,
),
],
),
);
}
}
String dummyData;
TextEditingController qrTextController = TextEditingController();

:: Scan Qr Code

Import import ‘package:barcode_scan/barcode_scan.dart’; and initialize the

String qrCodeResult; variable to store the result of the Qr code.

Creating a scan function

Future<void> _scan() async {
ScanResult codeSanner = await BarcodeScanner.scan();
}

BrcodeScanner class provides us scan() method to scan the Qr code. BarcodeScanner.scan() returns a ScanResult that contains the text return by the Qr Code scanner.

Setting up the result of the scanner to the qrCodeResult

Future<void> _scan() async {
ScanResult codeSanner = await BarcodeScanner.scan(),
);
setState(() {
qrCodeResult = codeSanner.rawContent;
});
}

Setting up the camera option

scan() method contains option a property that can be used to change the camera (eg. front Camera or Back Camera).

Future<void> _scan() async {
ScanResult codeSanner = await BarcodeScanner.scan(
options: ScanOptions(
useCamera: camera,
),
);
}
int camera = 1;

ScanOptions provides us useCamera property to change the camera type.

  1. useCamera takes an integer 1 or -1.
  2. If useCamera value is 1 then the front Camera works to scan the Qr code.
  3. If useCamera value is -1 then back camera works to scan the Qr code.

To switch the camera I have built the following logic:

appBar: AppBar(
title: Text("Scan using:" + (backCamera ? "Front Cam" : "Back Cam")),
actions: <Widget>[
IconButton(
icon: backCamera
? Icon(Ionicons.ios_reverse_camera)
: Icon(Icons.camera),
onPressed: () {
setState(() {
backCamera = !backCamera;
camera = backCamera ? 1 : -1;
});
},
)
],
),

Initializing the scan() function

IconButton(
icon: Icon(MaterialCommunityIcons.qrcode_scan),
onPressed: () {
_scan();
},
)

Displaying the result

Center(
child: Text(
(qrCodeResult == null) || (qrCodeResult == "")
? "Please Scan to show some result"
: "Result:" + qrCodeResult,
style: TextStyle(fontSize: 20.0, fontWeight: FontWeight.w900),
),
)

scan.dart

import 'package:barcode_scan/barcode_scan.dart';
import 'package:flutter/material.dart';
import 'package:flutter_vector_icons/flutter_vector_icons.dart';

class ScanPage extends StatefulWidget {
@override
_ScanPageState createState() => _ScanPageState();
}

class _ScanPageState extends State<ScanPage> {
String qrCodeResult;
bool backCamera = true;

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Scan using:" + (backCamera ? "Front Cam" : "Back Cam")),
actions: <Widget>[
IconButton(
icon: backCamera
? Icon(Ionicons.ios_reverse_camera)
: Icon(Icons.camera),
onPressed: () {
setState(() {
backCamera = !backCamera;
camera = backCamera ? 1 : -1;
});
},
),
IconButton(
icon: Icon(MaterialCommunityIcons.qrcode_scan),
onPressed: () {
_scan();
},
)
],
),
body: Center(
child: Text(
(qrCodeResult == null) || (qrCodeResult == "")
? "Please Scan to show some result"
: "Result:" + qrCodeResult,
style: TextStyle(fontSize: 20.0, fontWeight: FontWeight.w900),
),
));
}

Future<void> _scan() async {
ScanResult codeSanner = await BarcodeScanner.scan(
options: ScanOptions(
useCamera: camera,
),
);
setState(() {
qrCodeResult = codeSanner.rawContent;
});
}
}

int camera = 1;

Our app will look like this

Scan and generate Qr Code Demo App

:: GitHub Link

flutter-devs/qr_code_demo
A new Flutter application. This project is a starting point for a Flutter application. A few resources to get you…github.com


🌸🌼🌸 Thank you for reading. 🌸🌼🌸🌼

Feel free to connect with us:
And read more articles from FlutterDevs.com

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on Facebook, GitHub, Twitter, and LinkedIn for any flutter related queries.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences!.

Leave comment

Your email address will not be published. Required fields are marked with *.