Google ML Kit for Flutter
repository·develop·Indexed 22 days ago
https://github.com/flutter-ml/google_ml_kit_flutterA suite of plugins bridging Flutter applications with Google's standalone ML Kit for on-device machine learning. Includes packages such as google_mlkit_commons for image handling and google_mlkit_barcode_scanning for barcode processing. Provides guidance on native platform configuration for iOS (deployment target 15.5+, 64-bit architecture) and Android (minSdkVersion 21), as well as integrating with the Flutter camera plugin.
What's inside google_ml_kit_flutter
- Google's ML Kit for Flutter is a collection of Flutter plugins that allow developers to integrate Google's standalone ML Kit capabilities into Flutter applications. It provides access to various machine learning features including Vision, Natural Language, and GenAI APIs.
Use Google ML Kit GenAI Summarization
developThe
google_mlkit_genai_summarizationplugin allows you to generate summaries of articles and conversations as bulleted lists using Google's ML Kit GenAI Summarization API.Note: This API is currently only available on Android and requires devices with AICore support. It is built on top of AICore and may not work on all Android devices.
RecognizedText and its hierarchy
developThe
RecognizedTextobject contains the results of the text recognition process. It follows a hierarchical structure:RecognizedText: The top-level object containing the fulltextstring.TextBlock: Represents a block of text. ContainsboundingBox(Rect),cornerPoints(List<Point<int>>),text(String), andrecognizedLanguages(List<String>).TextLine: Represents a line within a block. Inherits getters fromTextBlock.TextElement: Represents an individual element (like a word) within a line. Inherits getters fromTextBlock.
Platform availability and limitations
developiOS
This feature is not available on iOS. It is currently only supported on Android.
Android
- The scanner leverages Google Play services for UI and ML models, resulting in low APK binary size impact.
- No camera permission is required from your Flutter app, as the scanner uses the permissions managed by Google Play services.
How the Face Detection plugin works
developThis plugin acts as a bridge between Flutter and Google's native ML Kit APIs using Platform Channels.
Key Concepts:
- No Dart-side Processing: No Machine Learning processing is performed in Dart/Flutter. All calls are passed to the native platform (using
MethodChannelon Android andFlutterMethodChannelon iOS) where they are executed by Google's native APIs. - Asynchronous Communication: Messages and responses are passed asynchronously to ensure the Flutter UI remains responsive.
- Debugging: If you encounter errors, first verify if the issue is reproducible in Google's native example apps. If it is, the issue lies with the native ML Kit API, not the Flutter plugin.
- No Dart-side Processing: No Machine Learning processing is performed in Dart/Flutter. All calls are passed to the native platform (using
How Google ML Kit for Flutter works
developThis project acts as a bridge between Flutter and Google's native ML Kit APIs. It uses Flutter Platform Channels to communicate between the Dart code and the native platform (Android/iOS).
Key Concepts:
- No Dart-side Processing: No Machine Learning processing is performed in Flutter/Dart. All calls are passed to the native platform via
MethodChannel(Android) orFlutterMethodChannel(iOS) and executed using Google's native APIs. - Asynchronous Communication: Messages and responses are passed asynchronously to ensure the user interface remains responsive.
- Platform Support: Google's ML Kit APIs are developed natively only for iOS and Android. This plugin does not support Web or other platforms.
Debugging Guidance:
Because the processing happens on the native side, if you encounter issues with an ML model, you should first determine if the issue is with the plugin or the native API:
- Run the official native example apps by Google for iOS and Android.
- If the issue is reproducible in the native Google apps, report the issue to Google.
- If the native apps work correctly but the Flutter plugin fails, report the issue to the plugin authors.
- No Dart-side Processing: No Machine Learning processing is performed in Flutter/Dart. All calls are passed to the native platform via
Understand the Google ML Kit Flutter architecture
developThe
google_mlkit_commonsplugin acts as a bridge between Flutter and Google's native ML Kit APIs.Key Concepts:
- Platform Channels: All Machine Learning processing is performed natively on iOS or Android. No ML processing happens in Dart/Flutter. The plugin uses
MethodChannel(Android) andFlutterMethodChannel(iOS) to pass messages asynchronously. - Debugging: Because processing happens on the native side, if you encounter errors with an ML model, you should first verify if the issue exists in Google's official native example apps. If the native apps work but the Flutter plugin fails, the issue is likely within the plugin's bridge implementation.
- Platform Channels: All Machine Learning processing is performed natively on iOS or Android. No ML processing happens in Dart/Flutter. The plugin uses
Configure iOS for On-Device Translation
developTo use the translation plugin on iOS, you must meet the following requirements:
- Minimum iOS Deployment Target: 15.5
- Xcode: 15.3.0 or newer
- Swift: 5
- Architecture: ML Kit does not support 32-bit architectures (
i386andarmv7). You must excludearmv7in your Xcode build settings.
Steps to exclude armv7:
- In Xcode, go to Project > Runner > Building Settings.
- Locate Excluded Architectures > Any SDK and add
armv7.
Podfile Configuration: Your
Podfilemust be configured to set the deployment target and exclude the unsupported architecture.platform :ios, '15.5' # or newer version ... # add this line: $iOSVersion = '15.5' # or newer version post_install do |installer| # add these lines: installer.pods_project.build_configurations.each do |config| config.build_settings["EXCLUDED_ARCHS[sdk=*]"] = "armv7" config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = $iOSVersion end installer.pods_project.targets.each do |target| flutter_additional_ios_build_settings(target) # add these lines: target.build_configurations.each do |config| if Gem::Version.new($iOSVersion) > Gem::Version.new(config.build_settings['IPHONEOS_DEPLOYMENT_TARGET']) config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = $iOSVersion end end end endUse the Prompt class to generate text
developThe
Promptclass is the primary interface for interacting with Google's ML Kit GenAI Prompt API. You can use it to generate text from simple text prompts or multimodal prompts (text combined with an image).Workflow:
- Initialize: Create an instance of
Prompt. - Check Status: Use
checkFeatureStatus()to see if the feature isavailableordownloadable. If it isdownloadable, you must calldownloadFeature()before running inference. - Run Inference: Use
runInference()with your text prompt. - Cleanup: Call
close()to release resources.
final prompt = Prompt(); // 1. Check status and handle downloads if necessary final status = await prompt.checkFeatureStatus(); if (status == FeatureStatus.downloadable) { await prompt.downloadFeature( onDownloadCompleted: () { // Start prompt generation }, ); } else if (status == FeatureStatus.available) { // Start prompt generation } // 2. Generate text final text = "Write a 3 sentence story about a magical dog."; final response = await prompt.runInference(text); print('Response: $response'); // 3. Release resources prompt.close();- Initialize: Create an instance of
Configure iOS requirements for Barcode Scanning
developTo use
google_mlkit_barcode_scanningon iOS, you must meet the following requirements:- Minimum iOS Deployment Target: 15.5
- Xcode: 15.3.0 or newer
- Swift: 5
- Architecture: ML Kit does not support 32-bit architectures (
i386andarmv7). You must excludearmv7in your Xcode build settings.
Steps to exclude armv7: Go to
Project > Runner > Building Settings > Excluded Architectures > Any SDK > armv7.Podfile Configuration: Ensure your
Podfilesets the platform to 15.5 or newer and includes the necessarypost_installhooks to excludearmv7and enforce the deployment target across all pods.platform :ios, '15.5' # or newer version ... # add this line: $iOSVersion = '15.5' # or newer version post_install do |installer| # add these lines: installer.pods_project.build_configurations.each do |config| config.build_settings["EXCLUDED_ARCHS[sdk=*]"] = "armv7" config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = $iOSVersion end installer.pods_project.targets.each do |target| flutter_additional_ios_build_settings(target) # add these lines: target.build_configurations.each do |config| if Gem::Version.new($iOSVersion) > Gem::Version.new(config.build_settings['IPHONEOS_DEPLOYMENT_TARGET']) config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = $iOSVersion end end end endEnable Apple Silicon iOS Simulator support
developOn Apple Silicon Macs running iOS 26+ simulators, Google's ML Kit pods may cause
flutter runto fail because they lackarm64-iphonesimulatorslices.To fix this, use the opt-in Podfile helper provided by
google_mlkit_commons. This helper relabels thearm64slice to match your current build target (Simulator or Device) automatically.Note: To fully revert this patch, you must remove the lines from your Podfile and run
pod deintegrate && pod install.# Near the top, after `require ... podhelper ...`: require File.expand_path( '.symlinks/plugins/google_mlkit_commons/ios/scripts/apple_silicon_simulator', __dir__, ) post_install do |installer| # ...your existing post_install code... # Add this line at the end: mlkit_apple_silicon_simulator_patch(installer) endUse a local custom TFLite model for Image Labeling
developYou can use a custom TensorFlow Lite model bundled with your app assets.
- Add the
.tflitemodel to yourpubspec.yamlassets. - Android Setup: Add the following to your
app/build.gradleto prevent Gradle from compressing the model file:android { aaptOptions { noCompress "tflite" } } - Copy the model from assets to the application support directory using a helper function.
- Initialize
ImageLabelerusingLocalLabelerOptionswith the model's file path.
// Helper to get model path Future<String> getModelPath(String asset) async { final path = '${(await getApplicationSupportDirectory()).path}/$asset'; await Directory(dirname(path)).create(recursive: true); final file = File(path); if (!await file.exists()) { final byteData = await rootBundle.load(asset); await file.writeAsBytes(byteData.buffer .asUint8List(byteData.offsetInBytes, byteData.lengthInBytes)); } return file.path; } // Usage final modelPath = await getModelPath('assets/ml/object_labeler.tflite'); final options = LocalLabelerOptions( confidenceThreshold: confidenceThreshold, modelPath: modelPath, ); final imageLabeler = ImageLabeler(options: options);- Add the