In today’s app landscape, the ability to scan barcodes and QR codes is a highly sought-after feature. From streamlining inventory management to simplifying payments, the uses are endless. Flutter, with its rich ecosystem and cross-platform capabilities, makes it easy to integrate such functionality. This article guides you through adding barcode and QR code scanning to your Flutter app.
Why Add Barcode and QR Code Scanning to Your Flutter App?
- Convenience: Simplifies tasks like entering product details, making payments, or accessing URLs.
- Efficiency: Speeds up data entry and reduces errors.
- User Experience: Provides a modern and intuitive way to interact with your app.
Getting Started
Before diving into the implementation, ensure you have Flutter installed and set up. If not, follow the official Flutter documentation.
Step 1: Adding the Necessary Dependency
We’ll be using the flutter_barcode_scanner
package, which provides a simple and effective way to scan barcodes and QR codes. Add the following line to your pubspec.yaml
file:
dependencies:
flutter_barcode_scanner: ^2.0.0 # Use the latest version
After adding the dependency, run flutter pub get
to install the package.
Step 2: Implementing the Scanner
Now, let’s implement the barcode and QR code scanner in your Flutter app.
import 'package:flutter/material.dart';
import 'package:flutter_barcode_scanner/flutter_barcode_scanner.dart';
class ScanScreen extends StatefulWidget {
@override
_ScanScreenState createState() => _ScanScreenState();
}
class _ScanScreenState extends State {
String _scanBarcode = 'Unknown';
Future scanBarcode() async {
String barcodeScanRes;
// Platform messages may fail, so we use a try/catch PlatformException.
try {
barcodeScanRes = await FlutterBarcodeScanner.scanBarcode(
'#ff6666', 'Cancel', true, ScanMode.BARCODE);
print(barcodeScanRes);
} catch (e) {
barcodeScanRes = 'Failed to get platform version.';
}
// If the widget was removed from the tree while the asynchronous platform
// message was in flight, we want to discard the reply rather than calling
// setState to update our non-existent appearance.
if (!mounted) return;
setState(() {
_scanBarcode = barcodeScanRes;
});
}
Future scanQRCode() async {
String barcodeScanRes;
try {
barcodeScanRes = await FlutterBarcodeScanner.scanBarcode(
'#ff6666', 'Cancel', true, ScanMode.QR);
print(barcodeScanRes);
} catch (e) {
barcodeScanRes = 'Failed to get platform version.';
}
if (!mounted) return;
setState(() {
_scanBarcode = barcodeScanRes;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Barcode scan')),
body: Builder(builder: (BuildContext context) {
return Container(
alignment: Alignment.center,
child: Flex(
direction: Axis.vertical,
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
onPressed: () => scanBarcode(), child: const Text('Start barcode scan')),
ElevatedButton(
onPressed: () => scanQRCode(), child: const Text('Start QR scan')),
Text('Scan result : $_scanBarcode\n', style: const TextStyle(fontSize: 20))
]));
}),
);
}
}
Step 3: Understanding the Code
- Import Statements:
import 'package:flutter/material.dart'; import 'package:flutter_barcode_scanner/flutter_barcode_scanner.dart';
These lines import the necessary Flutter packages and the
flutter_barcode_scanner
plugin. - Stateful Widget:
class ScanScreen extends StatefulWidget { @override _ScanScreenState createState() => _ScanScreenState(); } class _ScanScreenState extends State
{ String _scanBarcode = 'Unknown'; @override Widget build(BuildContext context) { ... } } This sets up a stateful widget to manage the state of the scan result.
- Scan Function:
Future
scanBarcode() async { String barcodeScanRes; try { barcodeScanRes = await FlutterBarcodeScanner.scanBarcode( '#ff6666', 'Cancel', true, ScanMode.BARCODE); print(barcodeScanRes); } catch (e) { barcodeScanRes = 'Failed to get platform version.'; } if (!mounted) return; setState(() { _scanBarcode = barcodeScanRes; }); } This function initiates the barcode scanning process. The
FlutterBarcodeScanner.scanBarcode
method takes several arguments:#ff6666
: The color of the scan line.Cancel
: The text displayed for the cancel button.true
: Show flash icon.ScanMode.BARCODE
: The scan mode. Can also use ScanMode.QR
- Build Method:
@override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Barcode scan')), body: Builder(builder: (BuildContext context) { return Container( alignment: Alignment.center, child: Flex( direction: Axis.vertical, mainAxisAlignment: MainAxisAlignment.center, children:
[ ElevatedButton( onPressed: () => scanBarcode(), child: const Text('Start barcode scan')), ElevatedButton( onPressed: () => scanQRCode(), child: const Text('Start QR scan')), Text('Scan result : $_scanBarcode\n', style: const TextStyle(fontSize: 20)) ])); }), ); } The
build
method defines the UI of the scan screen. It contains a button to trigger the scan and displays the result.
Step 4: Permissions
You need to ensure that your app has the necessary camera permissions. Add the following to your AndroidManifest.xml
(for Android):
For iOS, add the following to your Info.plist
:
NSCameraUsageDescription
This app needs camera access to scan barcodes
Customization
The flutter_barcode_scanner
package offers several options for customization:
- Line Color: Change the color of the scanning line.
- Cancel Button Text: Customize the text of the cancel button.
- Flash Mode: Toggle the flash programmatically.
- Scan Mode: Switch between barcode and QR code scanning.
Conclusion
Adding barcode and QR code scanning to your Flutter app enhances its functionality and user experience. The flutter_barcode_scanner
package simplifies this process, allowing you to integrate scanning capabilities quickly. Remember to handle permissions correctly and explore the customization options to tailor the scanner to your app’s design and needs. With these steps, you can create a modern, efficient, and user-friendly application.