Flutter: internationalization tutorials: Part 1 — JSON approach

If you are going to make a global app with flutter, then you are in the right place. :D

ThanhDat Vo
3 min readSep 24, 2018

Introduction

What we often require in internationalization are the translations for each locale and the placeholder function. In this article, I will help you with 3 ways to archive those requirements with your flutter project! But firstly, we should go through an overview:

In order to make readers easy to follow the different of 3 ways, 3 example projects result in a final app:

Final example

Preparation

Well, first of all, you may need to check the official document here.
An important note is that Google actually just embedded internationalization in MaterialApp class when this article is written. The properties in MaterialApp class to notice are:

  • locale: set current locale for the app
  • localizationsDelegates: list versions of these localizations by creating implementations of LocalizationsDelegate<WidgetsLocalizations> or LocalizationsDelegate<MaterialLocalizations> whose load methods return custom versions of WidgetsLocalizations or MaterialLocalizations
  • supportedLocales: limited locales can be used in the app
  • localeResolutionCallback: a hook to listen when user change the locale of the OS

Old school JSON way

If you come from the javascript world, you may be familiar with i18n.js and it’s JSON structure. If you want to share JSON translation between a javascript project and a dart project, then this way is better for you :D.

The app structure is as simple as below:

And the libraries and link assets:

First, of course, we should have translation resources:

Then, import JSON resources to our dart:

Next, let’s prepare our MyLocalizations and MyLocalizationsDelegate classes

Put attention to the getter hello and the method greetTo, that what we write to process translation of the word “hello” and “greetTo”. As you can see, the inconvenience of this approach is that we have to process every translation by code.

Finally, let link all the parts together in main.dart

Congratulations, you have finished the i18n with JSON resources. But you can see this has some pros and cons:

Pros

  • You can reuse the JSON resource in Angular and React / RN project

Cons

  • You have to process every translation by hand, which takes time, and a little bit hard to maintain

You can find full source code here

If this approach does not satisfy you, you may want to try with Dart and Android Studio plugin approaches in Part 2 and Part 3 respectively.

Hope you find this benefit you, and I’m happy to receive your feedback and some claps may make me proud too :D

Thanks for reading!

--

--