Category

Flutter Packages

Category

2 Examples: Scan, Generate & Share QR Code In Flutter

scan qr code flutter generate example
QR code is a special type of barcode. Most of the apps we use, have QR code scanning feature.

So if you are planning to add QR code reading or generating feature.

Then you are in the right place.

Scan QR Code In Flutter Example

flutter read qr code
Let’s create a simple QR scanning app using qr_code_scanner package. This package also provides

  • Turning on/off flashlight
  • Flip camera

You can achieve these features in just one line of code.

I assume you have created Flutter project, let’s add QR code dependency in pubspec.yaml file.

  • Dependency requires Android API 21. For iOS devices, requires iOS 8.

cupertino_icons: ^1.0.2
qr_code_scanner: ^0.5.1

Indentation is important.

For iOS devices


io.flutter.embedded_views_preview

NSCameraUsageDescription
Need to access Camera for scanning QR codes

In main.dart file, just import this dependecy in your code.


import 'package:qr_code_scanner/qr_code_scanner.dart';

  • In this example, There are 2 sections.
  • First section which holds QRView, flip camera and flash icons.
  • 2nd section for displaying QR code data.

Let’s learn about QRView widget.

QRView

QRView widget scans the QR code and return its information.

  • onQRViewCreated: When the view get’s created, it invokes with QRViewController. So we will use this property to get the QR code data and display it in Text.
  • overlay: Use this property to make a certain scan area. Using QrScannerOverlayShape, we can make a rectangular area.
    • Teal color used for border color.
    • As cutOutSize, we will use 80% of the width.
  • controller.flipCamera(): Flip FrontCamera/Backcamera.
  • controller.toggleFlash(): Turn on/off Flashlight

import 'dart:io';

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

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Scan QR Code - Flutter Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: ScanQRPage(),
    );
  }
}

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

  @override
  _ScanQRPageState createState() => _ScanQRPageState();
}

class _ScanQRPageState extends State {
  final GlobalKey qrKey = GlobalKey();
  late QRViewController controller;
  Barcode? result;
//in order to get hot reload to work.
  @override
  void reassemble() {
    super.reassemble();
    if (Platform.isAndroid) {
      controller.pauseCamera();
    } else if (Platform.isIOS) {
      controller.resumeCamera();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Scan QR Code - Flutter Example'),
      ),
      body: Column(
        children: [
          Expanded(
            flex: 4,
            child: Stack(
              children: [
                QRView(
                  key: qrKey,
                  onQRViewCreated: onQRViewCreated,
                  overlay: QrScannerOverlayShape(
//customizing scan area
                    borderWidth: 10,
                    borderColor: Colors.teal,
                    borderLength: 20,
                    borderRadius: 10,
                    cutOutSize: MediaQuery.of(context).size.width * 0.8,
                  ),
                ),
                Positioned(
                  left: 0.0,
                  right: 0.0,
                  bottom: 0.0,
                  child: Container(
                    width: 50,
                    height: 50,
                    decoration: BoxDecoration(
                      color: Colors.black26,
                    ),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        IconButton(
                            icon: Icon(
                              Icons.flip_camera_ios,
                              color: Colors.white,
                            ),
                            onPressed: () async {
                              await controller.flipCamera();
                            }),
                        IconButton(
                            icon: Icon(
                              Icons.flash_on,
                              color: Colors.white,
                            ),
                            onPressed: () async {
                              await controller.toggleFlash();
                            })
                      ],
                    ),
                  ),
                )
              ],
            ),
          ),
          Expanded(
            flex: 1,
            child: Container(
              margin: EdgeInsets.all(8.0),
              width: double.infinity,
              color: Colors.white,
              child: Center(
                child: result != null
                    ? Column(
                        children: [
                          Text('Code: ${result!.code}'),
                          SizedBox(
                            height: 8.0,
                          ),
                          Text('Format: ${result!.format}'),
                        ],
                      )
                    : Text('Scan Code'),
              ),
            ),
          ),
        ],
      ),
    );
  }

  void onQRViewCreated(QRViewController p1) 
{
//called when View gets created. 
    this.controller = p1;

    controller.scannedDataStream.listen((scanevent) {
      setState(() {
//UI gets created with new QR code.
        result = scanevent;
      });
    });
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }
}


QR Code Generator & Share Example

qr code generator share

In this example, You will learn how to generate a QR Code from given data in TextField using qr_flutter and Share it using share_plus.

path_provider: Used for finding usually used locations on filesystem.

Let’s add these packages in as dependencies in pubspec.yaml file.


  qr_flutter: ^4.0.0
  path_provider:
  share_plus: ^2.1.2

Use flutter pub get command.

Import these lines in your main.dart file.


import 'package:qr_flutter/qr_flutter.dart';
import 'package:path_provider/path_provider.dart';
import 'package:share_plus/share_plus.dart';

  • QrImage widget creates code using value in data property.
  • First ElevatedButton, resets UI with new QR code.
  • Share ElevatedButton creates a QR code image in app’s directory and share it with using Share_plus.
  • This example, stores qr image in app documents directory. You can also use temporary directory.
  • Share.shareFiles(): For sharing QR code image, we need to pass path of the image, type and text for sharing.

import 'dart:typed_data';
import 'dart:ui';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:qr_flutter/qr_flutter.dart';
import 'package:path_provider/path_provider.dart';
import 'package:share_plus/share_plus.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter QR Code Generator With Share',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: QRGeneratorSharePage(),
    );
  }
}

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

  @override
  _QRGeneratorSharePageState createState() => _QRGeneratorSharePageState();
}

class _QRGeneratorSharePageState extends State {
  final key = GlobalKey();
  String textdata = 'androidride.com';
  final textcontroller = TextEditingController();
  File? file;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: AppBar(
        title: Text('QR Code Generator With Share Example'),
      ),
      body: Column(
        children: [
          RepaintBoundary(
            key: key,
            child: Container(
              color: Colors.white,
              child: QrImage(
                size: 300,//size of the QrImage widget.
                data: textdata,//textdata used to create QR code
              ),
            ),
          ),
          SizedBox(
            height: 50,
          ),
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: TextField(
              controller: textcontroller,
            ),
          ),
          ElevatedButton(
            child: Text('Create QR Code'),
            onPressed: () async {
              setState(() {
//rebuilds UI with new QR code
                textdata = textcontroller.text;
              });
            },
          ),
          ElevatedButton(
            child: Text('Share'),
            onPressed: () async {
              try {
                RenderRepaintBoundary boundary = key.currentContext!
                    .findRenderObject() as RenderRepaintBoundary;
//captures qr image 
                var image = await boundary.toImage();

                ByteData? byteData =
                    await image.toByteData(format: ImageByteFormat.png);

                Uint8List pngBytes = byteData!.buffer.asUint8List();
//app directory for storing images.
                final appDir = await getApplicationDocumentsDirectory();
//current time
                var datetime = DateTime.now();
//qr image file creation
                file = await File('${appDir.path}/$datetime.png').create();
//appending data
                await file?.writeAsBytes(pngBytes);
//Shares QR image
                await Share.shareFiles(
                  [file!.path],
                  mimeTypes: ["image/png"],
                  text: "Share the QR Code",
                );
              } catch (e) {
                print(e.toString());
              }
            },
          )
        ],
      ),
    );
  }
}


flutter qr code

This QR image created using the above example.

That’s all for now. If you like this post, please share it.

Please disable your adblocker or whitelist this site!