QR Code Generator And Scanner Flutter

Ecco Suprastyo
6 min readDec 26, 2019

--

You can see FULL SECTION this article in this http://camellabs.com/flutter-json-array-parse-of-objects/.

The Example will show about QR Code Generator And Scanner Flutter. This article will creating a simple application using qr_flutter 3.1.0 package. The qr_flutter 3.1.0 package have features like that :

  • Built on QR — Dart
  • Automatic QR code version/type detection or manual entry
  • Supports QR code versions 1–40
  • Error correction / redundancy
  • Configurable output size, padding, background and foreground colors
  • Supports image overlays
  • Export to image data to save to file or use in memory
  • No internet connection required

You can read other article with flutter in this section :

First, we must create a project using Visual Studio Code software with name “barcode_scanner”. Let’s to create a new project using Visual Studio Code:

  1. Invoke View > Command Palette.
  2. Type “flutter”, and select the Flutter: New Project.
  3. Enter a project name, example such as “barcode_scanner”, and press Enter.
  4. Create or select the parent directory for the new project folder.
  5. Wait for project creation progress to complete and the main.dart file to appear.

Next, add the qr_flutter package to your project. The qr_flutter is a Flutter library for simple and fast QR code rendering via a Widget or custom painter.

dependencies: 
qr_flutter: <latest_version>

Then we click the get package, wait until the process is complete.

After we created pubspec.yaml , You must edit file with name main.dart like below :

import 'package:flutter/material.dart';
import 'home_screen.dart';
void main() => runApp(MyApp());class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'QR Generator-Scanner',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: HomeScreen(),
);
}
}

We will create home_screen.dart to default screen, Our home screen can be allow the user to select scan or generate QR Code by tapping on button. The widget will return a Column with 2 RaisedButton as the children, one of routing to generating QR code screen and one of routing to scanning QR code screen when the button is tapped. The home screen code like below:

import 'package:flutter/material.dart';
import 'package:barcode_scanner/scan.dart';
import 'package:barcode_scanner/generate.dart';
import 'package:flutter/rendering.dart';
class HomeScreen extends StatelessWidget { @override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: Text('QR Code Scanner & Generator'),
backgroundColor: Colors.deepOrange,
),
body: Center(
child:
Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Padding(
padding: EdgeInsets.symmetric(vertical: 8.0, horizontal: 16.0),
child: RaisedButton(
color: Colors.deepOrange,
textColor: Colors.white,
splashColor: Colors.blueGrey,
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => ScanScreen()),
);
},
child: const Text('SCAN QR CODE')
),
),
Padding(
padding: EdgeInsets.symmetric(vertical: 8.0, horizontal: 16.0),
child: RaisedButton(
color: Colors.deepOrange,
textColor: Colors.white,
splashColor: Colors.blueGrey,
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => GenerateScreen()),
);
},
child: const Text('GENERATE QR CODE')
),
),
],
)
),
);
}
}

For detail widget we need create detail.dart :

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'dart:io';
import 'dart:async';
class DetailWidget extends StatefulWidget { String _filePath;
DetailWidget(this._filePath);
@override
State<StatefulWidget> createState() {
return _DetailState();
}
}class _DetailState extends State<DetailWidget> { @override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Detail'),
actions: <Widget>[
IconButton(
icon: Icon(Icons.share),
onPressed: () {
final channel = const MethodChannel('channel:me.camellabs.share/share');
channel.invokeMethod('shareFile', 'image.png');
},
)
],
),
body: Container(
child: SizedBox(
height: 500.0,
child: new Center(
child: widget._filePath == null
? Text('No Image')
: Container(
child: Image.file(File(widget._filePath), fit: BoxFit.fitWidth))
),
),
)
);
}}

Create scan screen widget display the start scan with camera button and a Text widget that display the result of the camera QR code scan. It uses the Column Widget as the parent for the Text and Button children.

import 'dart:async';import 'package:barcode_scan/barcode_scan.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class ScanScreen extends StatefulWidget {
@override
_ScanState createState() => new _ScanState();
}
class _ScanState extends State<ScanScreen> {
String barcode = "";
@override
initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: new AppBar(
title: new Text('QR Code Scanner'),
backgroundColor: Colors.deepOrange,
),
body: new Center(
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Padding(
padding: EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
child: RaisedButton(
color: Colors.deepOrange,
textColor: Colors.white,
splashColor: Colors.blueGrey,
onPressed: scan,
child: const Text('START CAMERA SCAN')
),
)
,
Padding(
padding: EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
child: Text(barcode, textAlign: TextAlign.center,),
)
,
],
),
));
}
Future scan() async {
try {
String barcode = await BarcodeScanner.scan();
setState(() => this.barcode = barcode);
} on PlatformException catch (e) {
if (e.code == BarcodeScanner.CameraAccessDenied) {
setState(() {
this.barcode = 'The user did not grant the camera permission!';
});
} else {
setState(() => this.barcode = 'Unknown error: $e');
}
} on FormatException{
setState(() => this.barcode = 'null (User returned using the "back"-button before scanning anything. Result)');
} catch (e) {
setState(() => this.barcode = 'Unknown error: $e');
}
}
}

Create Generate screen widget displays a TextField for user enter the text data that will be used to generate the QR Code widget using the qr_flutter plugin when the user tap on the submit Button. It also provides a Share Button in the Navigation bar to share the image png file to other apps in iOS and Android.

import 'package:flutter/material.dart';
import 'package:qr_flutter/qr_flutter.dart';
import 'package:flutter/services.dart';
import 'dart:async';
import 'dart:typed_data';
import 'dart:ui';
import 'dart:io';
import 'package:flutter/rendering.dart';
import 'package:path_provider/path_provider.dart';
class GenerateScreen extends StatefulWidget { @override
State<StatefulWidget> createState() => GenerateScreenState();
}
class GenerateScreenState extends State<GenerateScreen> { static const double _topSectionTopPadding = 50.0;
static const double _topSectionBottomPadding = 20.0;
static const double _topSectionHeight = 50.0;
GlobalKey globalKey = new GlobalKey();
String _dataString = "Hello from this QR";
String _inputErrorText;
final TextEditingController _textController = TextEditingController();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('QR Code Generator'),
backgroundColor: Colors.deepOrange,
actions: <Widget>[
IconButton(
icon: Icon(Icons.share),
onPressed: _captureAndSharePng,
)
],
),
body: _contentWidget(),
);
}
Future<void> _captureAndSharePng() async {
try {
RenderRepaintBoundary boundary = globalKey.currentContext.findRenderObject();
var image = await boundary.toImage();
ByteData byteData = await image.toByteData(format: ImageByteFormat.png);
Uint8List pngBytes = byteData.buffer.asUint8List();
final tempDir = await getTemporaryDirectory();
final file = await new File('${tempDir.path}/image.png').create();
await file.writeAsBytes(pngBytes);
final channel = const MethodChannel('channel:me.camellabs.share/share');
channel.invokeMethod('shareFile', 'image.png');
} catch(e) {
print(e.toString());
}
}
_contentWidget() {
final bodyHeight = MediaQuery.of(context).size.height - MediaQuery.of(context).viewInsets.bottom;
return Container(
color: const Color(0xFFFFFFFF),
child: Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.only(
top: _topSectionTopPadding,
left: 20.0,
right: 10.0,
bottom: _topSectionBottomPadding,
),
child: Container(
height: _topSectionHeight,
child: Row(
mainAxisSize: MainAxisSize.max,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Expanded(
child: TextField(
controller: _textController,
decoration: InputDecoration(
hintText: "Enter a custom message",
errorText: _inputErrorText,
),
),
),
Padding(
padding: const EdgeInsets.only(left: 10.0),
child: FlatButton(
child: Text("SUBMIT"),
onPressed: () {
setState((){
_dataString = _textController.text;
_inputErrorText = null;
});
},
),
)
],
),
),
),
Expanded(
child: Center(
child: RepaintBoundary(
key: globalKey,
child: QrImage(
data: _dataString,
size: 0.5 * bodyHeight,

),
),
),
),
],
),
);
}
}

The application can be run to show output below :

For complete source code you can see flutter qr code scanner in Here.

Thank you for reading this article about QR Code Generator And Scanner Flutter, I hope this article is useful for you. Visit My Github about Flutter in Here.

--

--