Skip to content

Instantly share code, notes, and snippets.

@henriquedezani
Created May 30, 2019 12:14
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save henriquedezani/07ed36290f77af83638b59a0e62aa08d to your computer and use it in GitHub Desktop.
Save henriquedezani/07ed36290f77af83638b59a0e62aa08d to your computer and use it in GitHub Desktop.
Simple example using Flutter and Firebase MLKit (OCR)
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,
),
],
)
);
}
}
@bytespryte
Copy link

Thank you for writing this, it has inspired me to look further into this package

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment