Skip to main content

Command Palette

Search for a command to run...

How to Integrate Text Recognition (OCR) using Google ML Kit - Flutter AI Integration Demo.

Hey folks, Samuel from TechWithSam here. If you're building mobile apps in 2025, AI isn't a "nice-to-have" - it's essential. Think...

Updated
4 min read
How to Integrate Text Recognition (OCR) using Google ML Kit - Flutter AI Integration Demo.
S

Hello, I'm Samuel, also known as Tech With Sam.

I am passionate about learning and teaching programming, particularly Flutter and Dart at the moment. Please support me by subscribing to my newsletter. Thanks!

Subscribe for weekly tutorials and tips, or DM me to bring your app idea to life.

Questions? Join me on Discord: https://discord.gg/8X7dPYujqm For Business: techwithsam10@gmail.com

Hey folks, Samuel from TechWithSam here. If you’re building mobile apps in 2025, AI isn’t a “nice-to-have” — it’s essential. Think personalized recommendations, image analysis, or voice commands, all running smoothly on-device for speed and privacy. As a Flutter expert who’s shipped AI-powered apps for clients across Europe and the US, I’ve seen how Google ML Kit can supercharge your projects without the hassle of native code.

In this tutorial, we’ll integrate ML Kit’s text recognition into a simple Flutter camera app. You’ll scan text from photos and display it instantly. By the end, you’ll have a working demo ready to adapt for your startup’s inventory scanner or travel translator. Let’s dive in — code included!

Prerequisites

  • Flutter SDK (v3.24+).

  • Android Studio/Xcode for emulators.

  • Google ML Kit plugin (we’ll add it).

  • Basic Dart knowledge.

Run flutter create ai_flutter_demo to start a new project.

Step 1: Add Dependencies

Open pubspec.yaml and add the ML Kit plugin. It’s official and handles iOS/Android seamlessly.

dependencies:
  flutter:
    sdk: flutter
  google_mlkit_text_recognition: ^0.15.0  # Latest as of 2025
  camera: ^0.11.2  # For capturing images
  image: ^0.8.7+5   # Image processing

Run flutter pub get. For Android, add to android/app/build.gradle.kts:

android {
    compileSdk = 35
    ndkVersion = "27.0.12077973"
    defaultConfig {
        minSdk = 21 # ML Kit requires this
        targetSdk = 35
    }
}

For iOS, update Podfile with platform :ios, ‘16.0’. Pro tip: ML Kit works offline, perfect for global clients with spotty internet.

Step 2: Set Up Permissions

Users need camera access. In android/app/src/main/AndroidManifest.xml:

<uses-permission android:name="android.permission.CAMERA" />

For iOS, add to ios/Runner/Info.plist:

<key>NSCameraUsageDescription</key>
<string>Camera access for text recognition</string>

Request runtime permissions in your app (we’ll code this next).

Step 3: Initialize the Camera and ML Kit

Create lib/main.dart. We’ll use a StatefulWidget for the camera preview.

import 'package:flutter/material.dart';
import 'package:camera/camera.dart';
import 'package:google_mlkit_text_recognition/google_mlkit_text_recognition.dart';
import 'package:image/image.dart' as imglib;

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  final cameras = await availableCameras();
  runApp(MyApp(camera: cameras.first));
}

class MyApp extends StatelessWidget {
  final CameraDescription camera;
  const MyApp({super.key, required this.camera});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: CameraScreen(camera: camera),
    );
  }
}

class CameraScreen extends StatefulWidget {
  final CameraDescription camera;
  const CameraScreen({super.key, required this.camera});

  @override
  State<CameraScreen> createState() => _CameraScreenState();
}

class _CameraScreenState extends State<CameraScreen> {
  late CameraController _controller;
  final TextRecognizer _textRecognizer = TextRecognizer();
  String _recognizedText = '';

  @override
  void initState() {
    super.initState();
    _controller = CameraController(widget.camera, ResolutionPreset.high);
    _controller.initialize().then((_) => setState(() {}));
  }

  @override
  void dispose() {
    _controller.dispose();
    _textRecognizer.close();
    super.dispose();
  }

  Future<void> _recognizeText() async {
    if (!_controller.value.isInitialized) return;
    final image = await _controller.takePicture();
    final inputImage = InputImage.fromFilePath(image.path);
    final RecognizedText recognizedText = await _textRecognizer.processImage(inputImage);

    setState(() {
      _recognizedText = recognizedText.text;
    });
  }

  @override
  Widget build(BuildContext context) {
    if (!_controller.value.isInitialized) return const Scaffold(body: Center(child: CircularProgressIndicator()));

    return Scaffold(
      body: Stack(
        children: [
          CameraPreview(_controller),
          Positioned(
            bottom: 50,
            left: 0,
            right: 0,
            child: Center(
              child: ElevatedButton(
                onPressed: _recognizeText,
                child: const Text('Scan Text'),
              ),
            ),
          ),
          if (_recognizedText.isNotEmpty)
            Positioned(
              top: 50,
              left: 20,
              right: 20,
              child: Container(
                padding: const EdgeInsets.all(10),
                color: Colors.black54,
                child: Text(_recognizedText, style: const TextStyle(color: Colors.white)),
              ),
            ),
        ],
      ),
    );
  }
}

This sets up a camera preview with a scan button. When pressed, it captures an image and runs ML Kit’s text recognition.

Step 4: Handle Permissions and Errors

Wrap the button in a permission check using the permission_handler package (add to pubspec if needed). Example:

import 'package:permission_handler/permission_handler.dart';

Future<void> _requestPermission() async {
  if (await Permission.camera.request().isGranted) {
    _recognizeText();
  } else {
    // Show dialog: "Camera access needed for AI features"
  }
}

Update the buttons onPressed to _requestPermission().

Common error: “No text detected”? Ensure good lighting — add a tip in your app’s UX.

Step 5: Test and Deploy

Run flutter run on an emulator/device. Snap a photo of text (e.g., a book page) — watch the magic! For production:

  • Optimize: Use isolates for heavy processing.

  • Scale: Integrate with Firebase for cloud ML if on-device isn’t enough.

  • 2025 Twist: Combine with Dart’s new AI libs for custom models.

Troubleshooting

  • Plugin conflicts? Clean/rebuild: flutter clean && flutter pub get.

  • iOS build fails? Update CocoaPods: pod install.

  • Low accuracy? Pre-process images with the image package for contrast.

There you have it — a Flutter app with AI smarts in under 100 lines! This setup saved one of my clients 40% on dev time for their e-commerce scanner. What’s your next AI feature? Drop a comment below.

Full Source Code 👇 — Show some ❤️ by starring ⭐ the repo and follow me 😄!

https://github.com/techwithsam/ai_flutter_demo

I hope you have learned something. Press the follow button if you’re not following me yet. Also, make sure to subscribe to the newsletter so you're notified when I publish a new article. Kindly press the live button as many times as you want if you enjoy it, and feel free to drop a comment.

If you need custom AI integration for your app, DM me at TechWithSam — let’s build something epic. Follow for more Flutter tips!

🔗 Let’s Connect 🔗 → Github | Twitter | Youtube | LinkedIn | Devto | Substack | Medium .

Join my Community 👨‍💻👨‍💻 on Discord.

Subscribe to my YouTube channel | and also to the Hashnode newsletter in the input box above👆 or below👇.

Happy Building! 🥰👨‍💻