-
-
Save Tebalo/175f69c9da6be86bf2b03aed9b1cddc5 to your computer and use it in GitHub Desktop.
Simple example using Flutter and Firebase MLKit (OCR)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:io'; | |
import 'package:flutter/material.dart'; | |
import 'package:image_picker/image_picker.dart'; | |
import 'package:firebase_ml_vision/firebase_ml_vision.dart'; | |
import 'package:translator/translator.dart'; | |
void main() => runApp(MyApp()); | |
class MyApp extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
title: 'Realtime translation', | |
theme: ThemeData( | |
primarySwatch: Colors.blue, | |
), | |
home: MyHomePage(title: 'Realtime translation'), | |
); | |
} | |
} | |
class HomePage extends StatefulWidget { | |
MyHomePage({Key key, this.title}) : super(key: key); | |
final String title; | |
@override | |
HomePageState createState() => HomePageState(); | |
} | |
class HomePageState extends State<HomePage> { | |
File _pickedImage; | |
bool _isImageLoaded = false; | |
bool _isTextLoaded = false; | |
String _text = ""; | |
Future pickImage() async { | |
var tempStore = await ImagePicker.pickImage(source: ImageSource.gallery); | |
setState(() { | |
_pickedImage = tempStore; | |
_isImageLoaded = true; | |
}); | |
} | |
Future readText() async { | |
FirebaseVisionImage ourImage = FirebaseVisionImage.fromFile(_pickedImage); | |
TextRecognizer recognizeText = FirebaseVision.instance.textRecognizer(); | |
VisionText readText = await recognizeText.processImage(ourImage); | |
translate(readText.text); | |
} | |
void translate(String readText) async { | |
GoogleTranslator translator = GoogleTranslator(); | |
String input = readText; | |
translator.translate(input, to: 'pt') | |
.then((_translatedText) => { | |
setState(() { | |
_text = _translatedText; | |
_isTextLoaded = true; | |
}); | |
}); | |
} | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
appBar: AppBar( | |
title: Text(widget.title), | |
), | |
body: Column( | |
children: <Widget>[ | |
_isImageLoaded ? Center( | |
child: Container( | |
height: 200.0, | |
width: 200.0, | |
decoration: BoxDecoration( | |
image: DecorationImage( | |
image: FileImage(pickedImage), fit: BoxFit.cover) | |
), | |
), | |
) : Container(), | |
_isTextLoaded ? Center( | |
child: Text(_text) | |
) : Container(), | |
SizedBox(height: 10.0,), | |
RaisedButton( | |
child: Text('Choose an image'), | |
onPressed: pickImage, | |
), | |
SizedBox(height: 10.0,), | |
RaisedButton( | |
child: Text('Read Text'), | |
onPressed: readText, | |
), | |
], | |
) | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment