How to translate text in Flutter using Google Translate API (Properly)

Flutter and Google Translate API EASIER!!

In this article i’m gonna show a great and very simple way to translate the texts in your app using the Google Translate API and the package: google_translator.

1) Get the API Key

  1. Enable your the Cloud Translation API;
Sample 1

3. Go to Credentials and create one;

4. Select the Api Key option;

5. Now, here’s the key.

Sample 2

2) implement the API

Add dependency:

dependencies:
# Functionalities
google_translator: ^{latest version}
..
flutter:
sdk: flutter

Add the following imports to your Dart code:

import 'package:google_translator/google_translator.dart';

Getting Started

void main() {
/// Required to make the `GoogleTranslatorInit` call before the `MaterialApp`
WidgetsFlutterBinding.ensureInitialized();
runApp(MyApp());
}
class MyApp extends StatelessWidget { final String apiKey = "YOUR_GCP_API_KEY"; @override
Widget build(BuildContext context) {
return GoogleTranslatorInit(apiKey,
translateFrom: Locale('pt-br'),
translateTo: Locale('en'),
// automaticDetection: , In case you don't know the user language will want to traslate,
// cacheDuration: Duration(days: 13), The duration of the cache translation.
builder: () => MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Página inicial de demonstração do Flutter'),
),
);
}
}

Note: If will want to make the call before the MaterialApp, will have to add the WidgetsFlutterBinding.ensureInitialized(); before the runApp function.

Basic Usage

Scaffold(
appBar: AppBar(
title: Text(widget.title ?? "").translate(),
),
body: Column(
children: [
Text("Meu texto traduzido").translate(),
Text("Este texto mostra um placeholder diferente").translate("Place to Holder")
]
),
);

It’s easy as that.