Google ML Kit + Flutter: Part 1 (Barcode Scanning)
Hello Flutter Developer π, welcome to a new article on the barcode scanning use-case of the Google ML Kit library in Flutter!
The Google ML Kit is a powerful and easy-to-use machine learning framework that allows developers to add various machine learning features to their Flutter apps. One of its most useful features is barcode scanning, which enables your app to quickly and accurately read barcodes and QR codes from images or live camera feeds.
In this article, we will dive into the world of barcode scanning and explore how the Google ML Kit library can help us add this functionality to our Flutter app.
Implementation:
Step 1: Add the dependencies
Add dependencies to pubspec.yaml file.
dependencies:
flutter:
sdk: flutter
google_ml_kit: ^0.13.0
image_picker: ^0.8.6
Step 2: Import
import 'package:google_ml_kit/google_ml_kit.dart';
import 'package:image_picker/image_picker.dart';
Step 3: Install the dependencies
Run the below command in the root directory of your app to install dependency.
flutter pub get
Step 4: Initialize BarcodeScanner Instance
There are two ways to create instances of BarcodeScanner.
a) First way to create an instance of barCodeScannerar
is by using barcodeScanner() method of GoogleMlKit.vision
final barCodeScanner = GoogleMlKit.vision.barcodeScanner();
b) Second way to create an instance is to directly use BarcodeScanner() with the required formats.
final barcodeScanner = BarcodeScanner(formats: [BarcodeFormat.all]);
Step 5: Picking Image & Processing
Whenever the user picks or captures any image then we will process that image using the processImage() method of barcodeScanner instance.
And after getting the identified text we will assign it to the text for display
try {
var file =
await ImagePicker.platform.pickImage(source: ImageSource.camera);
setState(() {
text = 'processing...';
});
var barCodeScanner = GoogleMlKit.vision.barcodeScanner();
final visionImage = InputImage.fromFilePath(file!.path);
var barcodeText= await barCodeScanner.processImage(visionImage);
for(Barcode barcode in barcodeText){
setState(() {
text = barcode.displayValue!;
});
}
} catch (e) {
log(e.toString());
setState(() {
text = e.toString();
});
}
Output:
Full Souce Code
Here is the source code that you can clone and use for your application.
GitHub Link: BarcodeScanning
Please Follow π and clap π, if you find the article useful. And get notified of my upcoming articles.
Follow me on Twitter: @imsnehalsingh and Github: Snehal Singh to hear about my projects.