Communication is a miracle of translation…

Fluttering into the Google World over some time and decided to go for Translation……

Begin…

For the translation part, we need to introduce Google Cloud Translation API.

As per the docs, 

The Translation API translates input into any supported language using state-of-the-art Neural Machine Translation. 

Flutter and Google Translation API..
Flutter and Google Translation API..

What do we need : 

  1. Google Project in the Google Cloud Console.
  2. Enable Google Cloud Translation API.
Enable Google Cloud Translation API…
Enable Google Cloud Translation API…

3. Create a credentials key for your account..

Navigate to the API Manager section of your project dashboard,

Create Credentials…
Create Credentials…

In the drop down menu, select API key:

API Key…
API Key…

Send requests to Cloud Translation API…

  1. Need to create a URI based on the API key (from above)
https://translation.googleapis.com/language/translate/v2?target={YOUR_LANGUAGE}&key=${API_KEY}&q=${TEXT}

Parameters :

  1. target={YOUR_LANGUAGE}

Replace this to the language, you want for your text. e.g If the output required is in Spanish, then target=es

2. key=${API_KEY}

Replace this to your api key from above steps. e.g If key is 1234567, then key=1234567

3. q=${TEXT}

Replace this to your text you want to be translated. e.g Say “hello”, then q=hello

No headers etc required. Just the above params.

Flutter and Google Translate API….
Flutter and Google Translate API….

Response….

Your response should look like the following:

{  "data": {    "translations": [      {        "translatedText": "TRANSLATED TEXT",        "detectedSourceLanguage": "DETECTED SOURCE LANGUAGE"      }    ]  }}

Note : TRANSLATED TEXT and DETECTED SOURCE LANGUAGE

will be replaced by actual response from API…


Enter Flutter…

For constructing the url in Flutter, I would recommend using Uri class.

There is an inbuilt option in Flutter under dart:core as Uri.https

Creates a new https URI from authority, path and query.

This constructor is the same as Uri.http except for the scheme which is set to https.

Uri.https(
String authority,
String unencodedPath,
[ Map<String, String> queryParameters ]
)

where authority is e.g stackoverflow.com and not https://stackoverflow.com

where unencodedPath is /questions/sdsdssa

where queryParameters are : in our case the 3 params above.

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *