How to scan QR code with Flutter

First, we’ll need to import the qrcode_reader package from pub.dev.

Add the following to your pubspce.yaml file

qrcode_Reader: any

Create a new Dart file and paste this code:

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

 class ScanQRCode extends StatefulWidget {
   @override
   _ScanQRCodeState createState() => _ScanQRCodeState();
 }

 class _ScanQRCodeState extends State<ScanQRCode> {
   String scannedString = '';

   _scanQR() async {
     setState(() async {
       scannedString = await new QRCodeReader().scan();
     });
   }

   @override
   Widget build(BuildContext context) {
     return Scaffold(
       appBar: AppBar(title: Text('Scan QR Code example')),
       body: Center(
         child: scannedString == null || scannedString.isEmpty
             ? RaisedButton(
                 child: Text('Scan QR Code'),
                 color: Colors.red,
                 onPressed: _scanQR,
               )
             : Text(
                 scannedString,
                 style: TextStyle(
                   fontSize: 17.0,
                   fontWeight: FontWeight.bold,
                 ),
               ),
       ),
     );
   }
 }

In your main.dart file:

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Code Snippets',
      theme: new ThemeData(primarySwatch: Colors.red),
      home: new ScanQRCode();
}
}

Add a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.