Ferid Cafer
Etiya
Published in
2 min readSep 8, 2023

--

Flutter using Google ML-Kit

Using Google’s ML-Kit is really simple.

First of all add ML-Kit library into pubspec.yaml. Besides, to be able to use camera easily, I added camera_camera library, too.

google_ml_kit: ^0.16.2
camera_camera: ^3.0.0

Barcode & QR Code

To read barcodes and QR codes, we need to use BarcodeScanner.

BarcodeScanner barcodeScanner = BarcodeScanner();

After the above declaration, now, we can call the method to read barcode. Be aware that, the method is to be async.

/// Scan barcode or QR code
Future<void> scanBarcode() async {
List<String?> barcodes = [];

InputImage image = InputImage.fromFile(imageFile);

List<Barcode> barcodeList = await barcodeScanner.processImage(image);

if (barcodeList.isNotEmpty) {
for (Barcode barcodeLabel in barcodeList) {
barcodes.add(barcodeLabel.rawValue);
}
}
}

Text Recognition

Text recognition will yield the ability of parsing texts just from images.

To start, let us declare our variable.

TextRecognizer recognizer = TextRecognizer();

Now, call the necessary method to start reading texts.

/// Detect texts
Future<void> fetchText() async {
List<String> parsedTextList = [];

InputImage image = InputImage.fromFile(imageFile);

RecognizedText recognisedText = await recognizer.processImage(image);

for (TextBlock block in recognisedText.blocks) {
for (TextLine line in block.lines) {
parsedTextList.add(line.text);
}
}
}

Image Labeling

Image labeling reads the features of an image.

To declare image labeler, first, we need to declare image labeler options.

final ImageLabelerOptions options = ImageLabelerOptions(confidenceThreshold: 0.5);
late ImageLabeler imageLabeler;

Here, we gave a confidence threshold of %50. This means, the detected features with minimum %50 probability will be retrieved from the library. Features that are detected with lower probability (confidence) will not be listed.

/// Read labels
Future<void> readImageLabels() async {
List<String> imageLabels = [];

InputImage image = InputImage.fromFile(imageFile);

imageLabeler = ImageLabeler(options: options);
List<ImageLabel> labels = await imageLabeler.processImage(image);

for (ImageLabel label in labels) {
imageLabels.add(label.label);
print("Feature: ${label.label} with confidence of ${label.confidence}");
}
}

That is all.

Please do not forget to close ML-Kit variables during dispose.

@override
void dispose() {
barcodeScanner.close();
recognizer.close();
imageLabeler.close();

super.dispose();
}

By the way, let us see the easy usage of camera_camera, too.

void openCamera() {
Navigator.push(
context,
MaterialPageRoute(
builder: (_) => CameraCamera(
onFile: (file) {
imageFile = file;
Navigator.pop(context);
// todo call your ml-kit method here
},
)));
}

That is all for calling camera retrieving the photo file which was taken with the device’s camera.

--

--