#3 Image to Text in Flutter App (Flutter Series by Akshit Madan)
Hey there, this is Akshit and in this module we are going to see how you can implement Image to Text model in your Flutter App using ML Vision Kit by Firebase.
- Connect your App to Firebase
- Add google_services.json file in the app Folder.
- Add firebase_ml_vision: ^0.9.6+2 dependency in pubspec.yaml.
- Add image_picker: dependency in pubspec.yaml.
- Lets code !!
main.dart
import 'package:flutter/material.dart';
void main() => runApp(new MyApp()); class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
brightness: Brightness.light,
primaryColor: Colors.purple,
debugShowCheckedModeBanner: false,
home: ImagetoText(),
);
}
}
image_to_text.dart
In this class define a Scaffold with a floating action button which triggers getimagefromgallery() function in which an image is picked from gallery using image_picker package.
getimagefromgallery() async {
var tempstore = await ImagePicker.pickImage(source: ImageSource.gallery);
setState(() {
pickedfile = File(tempstore.path);
imageloaded = true;
text = '';
});
readtextfromimage();
Now readtextfromimage() function will run
The TextRecognizer class of Firebase ML Vision Kit processes the image and reads the text present in image in the form of blocks which is a set of lines. A line is further a set of elements. An element contains words , so using nested for loops all the words can be diffrentiated and printed in the Text widget with a separation of space for diffrentiating one word from another.
readtextfromimage() async {FirebaseVisionImage myimage = FirebaseVisionImage.fromFile(pickedfile);TextRecognizer textRecognizer = FirebaseVision.instance.textRecognizer();VisionText readtext = await textRecognizer.processImage(myimage);for (TextBlock block in readtext.blocks) { for (TextLine line in block.lines) { for (TextElement word in line.elements) { setState(() { text = text + ' ' + word.text;
}); }
} }}
Now lets see how the widget tree and the whole file looks like ..
Thanks for reading…😉