Open In App

Flutter – QR Code Scanner and QR Generator

Last Updated : 21 Aug, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Accessing websites, images, and files using QR codes is widely used these days. These QR Codes are used for doing payments which is easy to use. You can see this feature in various payment apps such as Google Pay, Amazon Pay, and many more. In today’s article, we are going to see how to generate QR codes for certain links and QR code scanners in the flutter app.

Follow the below steps to build a simple QR scanner and generator app in Flutter:

Step 1: First add the following dependency in your pubspec.yaml file

Dart




dependencies:
   
  path_provider: ^1.6.24
  qr_flutter: ^3.2.0
  barcode_scan_fix: ^1.0.2


 Now click on pub.get to configure. 

Step 2: Now navigate to main.dart() file and return Material App()

First, we have declared MyApp() in runApp in the main function. Then we have created StatelessWidget for MyApp in which we have returned MaterialApp(). In this MaterialApp() we have given the title of our App then declared the theme of our App as primarySwatch as indigo. Then we have given our first screen of or slider app in the home: HomePage()

Dart




void main() {
  runApp(MyApp());
}
 
class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      //Given Title
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      //Given Theme Color
      theme: ThemeData(
       primarySwatch: Colors.indigo,
      ),
      //Declared first page of our app
      home: HomePage(),
    );
  }
}


Step 3: Declare StatefulWidget() for HomePage 

In StatefulWidget() return Scaffold() widget. In Scaffold() Widget in the body section, we have declared Container() having width and height. In that Container() we have given Column inside which we have given mainAxisAlignment as center and CrossAxisAlignment as a stretch. After that we have given an Image as Network Image below that Image we have given rounded FlatButton() having color, border-radius, and border side. On that FlatButton we have given onPressed method which is used to navigate to the next screen ScanQR().

Below that we have given another rounded FlatButton() having color, border-radius, and border side.  On that FlatButton we have given onPressed method which is used to navigate to the next screen GenerateQR().

Dart




class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}
 
class _HomePageState extends State<HomePage> {
 
  @override
  Widget build(BuildContext context) {
    return Scaffold(
     
      body: Container(
        width: 500,
        height: 500,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            //Display Image
             
            //First Button
            FlatButton(
              padding: EdgeInsets.all(15),
              onPressed: (){
                Navigator.of(context).push(MaterialPageRoute(builder: (context)=> ScanQR()));
              },
                child: Text("Scan QR Code",style: TextStyle(color: Colors.indigo[900]),),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(20),
                side: BorderSide(color: Colors.indigo[900]),
              ),
            ),
            SizedBox(height: 10),
 
            //Second Button
            FlatButton(
              padding: EdgeInsets.all(15),
              onPressed: (){
                Navigator.of(context).push(MaterialPageRoute(builder: (context)=>
                                                             GenerateQR()));
              },
              child: Text("Generate QR Code", style: TextStyle(color: Colors.indigo[900]),),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(20),
                side: BorderSide(color: Colors.indigo[900]),
              ),
            ),
          ],
        ),
      )
    );
  }
}


Step 4: Navigating to ScanQR() page.

In this file first, we have imported package barcode_scan_fix. Then we have created StateFulWidget for ScanQR class. In that state we have declared String as qrcoderesult = ‘Not yet Scanned’. After that in Scaffold() we have declared Appbar with the title. In the body section, we have declared Column() wrapped with Container() and given mainAxisAlignment as center and CrossAxisAlignment as a stretch. After that, we have declared two text widgets first text widget has declared for the given title. And the second text widget is used to declare the String which we have given. After that, we have given a FlatButton() and on its onPressed method, we have given codeScanner which is used to scan QR code which we have imported from the bar_code_scan_fix library.

Dart




import 'package:barcode_scan_fix/barcode_scan.dart';
import 'package:flutter/material.dart';
 
class ScanQR extends StatefulWidget {
  @override
  _ScanQRState createState() => _ScanQRState();
}
 
class _ScanQRState extends State<ScanQR> {
 
  String qrCodeResult = "Not Yet Scanned";
 
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Scan QR Code"),
      ),
      body: Container(
        padding: EdgeInsets.all(20),
    child: Column(
    mainAxisAlignment: MainAxisAlignment.center,
    crossAxisAlignment: CrossAxisAlignment.stretch,
    children: [
      //Message displayed over here
      Text(
        "Result",
        style: TextStyle(fontSize: 25.0, fontWeight: FontWeight.bold),
        textAlign: TextAlign.center,
      ),
      Text(
        qrCodeResult,
        style: TextStyle(
          fontSize: 20.0,
        ),
        textAlign: TextAlign.center,
      ),
      SizedBox(
        height: 20.0,
      ),
 
      //Button to scan QR code
      FlatButton(
        padding: EdgeInsets.all(15),
        onPressed: () async {
          String codeSanner = await BarcodeScanner.scan();    //barcode scanner
          setState(() {
            qrCodeResult = codeSanner;
          });
        },
        child: Text("Open Scanner",style: TextStyle(color: Colors.indigo[900]),),
        //Button having rounded rectangle border
        shape: RoundedRectangleBorder(
          side: BorderSide(color: Colors.indigo[900]),
          borderRadius: BorderRadius.circular(20.0),
        ),
      ),
 
         ],
        ),
      ),
    );
  }
}


Step 5: Navigating to GenerateQr() page.

First we have given StateFulWidget() for GenerateQr() class. In that, we have given the final variable as TextEditingController(). In the Scaffold() section we have given appbar along with the title. In the body section, we have given Container() having Column() with mainAxisAlignment as center and CrossAxisAlignment as a stretch. Wrapped with SingleChildScrollView(). After that, we have given TextField() for giving input link to convert into a barcode. After that, we have given FlatButton() which will convert our link into a QR code. In the onPressed of this FlatButton() we have declared its logic in which the imported library qr_link is used to convert the link into QR code.

Dart




import 'package:flutter/material.dart';
import 'package:qr_flutter/qr_flutter.dart';
 
class GenerateQR extends StatefulWidget {
  @override
  _GenerateQRState createState() => _GenerateQRState();
}
 
class _GenerateQRState extends State<GenerateQR> {
 
  String qrData="https://github.com/ChinmayMunje";
  final qrdataFeed = TextEditingController();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      //Appbar having title
      appBar: AppBar(
        title: Center(child: Text("Generate QR Code")),
      ),
      body: Container(
        padding: EdgeInsets.all(20),
        child: SingleChildScrollView(
           
          //Scroll view given to Column
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              QrImage(data: qrData),
              SizedBox(height: 20),
              Text("Generate QR Code",style: TextStyle(fontSize: 20),),
               
              //TextField for input link
              TextField(
                decoration: InputDecoration(
                  hintText: "Enter your link here..."
                ),
              ),
              Padding(
                padding: const EdgeInsets.all(8.0),
                //Button for generating QR code
                child: FlatButton(
                    onPressed: () async {
                      //a little validation for the textfield
                      if (qrdataFeed.text.isEmpty) {       
                        setState(() {
                          qrData = "";
                        });
                      } else {
                        setState(() {
                          qrData = qrdataFeed.text;
                        });
                      }
                    },
                  //Title given on Button
                    child: Text("Generate QR Code",style: TextStyle(color: Colors.indigo[900],),),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(20),
                    side: BorderSide(color: Colors.indigo[900]),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}


Output:



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads