native_text_recognition 0.0.2
native_text_recognition: ^0.0.2 copied to clipboard
A Flutter package for native text recognition using native APIs.
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:native_text_recognition/native_text_recognition.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'native_text_recognition Example',
theme: ThemeData(useMaterial3: true, colorSchemeSeed: Colors.indigo),
home: const HomePage(),
);
}
}
class HomePage extends StatefulWidget {
const HomePage({super.key});
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
final _controller = TextEditingController();
final _ocr = NativeTextRecognition();
final _picker = ImagePicker();
String _status = 'Idle';
String _result = '';
bool _busy = false;
Future<void> _pickImage() async {
try {
final xfile = await _picker.pickImage(source: ImageSource.gallery);
if (xfile != null) {
_controller.text = xfile.path;
setState(() {});
}
} catch (e) {
setState(() => _status = 'Picker error: $e');
}
}
Future<void> _run() async {
final path = _controller.text.trim();
if (path.isEmpty) {
setState(() => _status = 'Enter an absolute image path');
return;
}
setState(() {
_busy = true;
_status = 'Running OCR...';
_result = '';
});
try {
final text = await _ocr.recognizeText(path);
setState(() {
_status = 'Done';
_result = text;
});
} catch (e) {
setState(() {
_status = 'Error: $e';
});
} finally {
setState(() => _busy = false);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Text Recognition Example')),
body: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Row(
children: [
Expanded(
child: TextField(
controller: _controller,
decoration: const InputDecoration(
labelText: 'Image absolute path',
hintText: '/path/to/image.jpg',
),
),
),
const SizedBox(width: 8),
IconButton(
tooltip: 'Pick image',
onPressed: _busy ? null : _pickImage,
icon: const Icon(Icons.photo_library_outlined),
),
],
),
const SizedBox(height: 12),
FilledButton.icon(
onPressed: _busy ? null : _run,
icon: const Icon(Icons.text_snippet_outlined),
label: const Text('Recognize Text'),
),
const SizedBox(height: 12),
Text(_status, style: Theme.of(context).textTheme.bodySmall),
const Divider(height: 24),
Expanded(
child: SingleChildScrollView(
child: SelectableText(
_result.isEmpty ? 'No result' : _result,
style: const TextStyle(fontFamily: 'monospace'),
),
),
),
],
),
),
);
}
}