Building a multi-language Flutter app with Easy Localization

August 29, 2022

Building a multi-language Flutter app with Easy Localization

With ever-growing global audiences, the majority of modern mobile applications require a certain level of international language support. When an application purely caters for an English market, its developer and their clients miss out on large download volumes from countries with a large population of mobile users. These include Saudi Arabia, Spain and Brazil, just to name a few. Mobile app users want to be communicated with and consume content in their native language as it allows each user to get involved and connect on a deeper level with the product they are using and the company behind it.

At Swipe iX, we have been developing mobile applications like this by using a software development kit (SDK) called Flutter. This SDK hosts a multitude of very powerful libraries and plugins, and among them lies a standout package called easy_localization 3.0.1. Easy Localization assists with translating texts within your mobile application, with little to no effort required from the developer.

In this article we will cover:

  • Installation
  • Asset setup
  • Initial setup
  • Basic translation
  • Advanced translation extension methods

Installation

To get started, add the plugin dependency to your pubspec.yaml file and then run the package’s get command.

 dependencies:
  easy_localization:         3.0.1>

Always ensure you have the latest version of the package in order to take full advantage of improvements. Once that has been done, import the plugin to your dart file.

import 'package:easy_localization/easy_localization.dart';

Assets

For the next step, create an assets folder within the root directory of your project, and a folder called translations inside this assets folder. This directory will be used to house your various JSON language files. In the example below, the first translation file is called en-US.json (English) and the second es-ES.json (Spanish). Inside each of these files is JSON data containing language keys and the individual translations pertaining to that specific language.

TIP: It’s good practice to keep all your strings inside these translation files lowercase. With extension methods, you can manipulate these to be displayed in CapitalCase or UpperCase in different areas of your application according to the use case.

To include assets in your application’s compilation we need to add the assets folder in the pubspec.yaml file inside the project.

assets:
 - assets/translations/

Initial setup

Flutter applications start with a main() function. Inside this function, we need to ensure that the plugin is initialised with the following:

await EasyLocalization.ensureInitialized();

The step we take after this is to initialise the plugin and provide some startup and configuration information. We supply the various desired locales that need to be supported. In this case, we are wanting to support both English and Spanish.

TIP: If the framework tries to load a specific locale from one of the supportedLocales, it will default back to the fallbackLocale property.

The path property is the location of your language asset files, as below:

runApp(
 EasyLocalization(
     supportedLocales: const [Locale('en', 'US'), Locale('es', 'ES')],
     path: 'assets/translations', // <-- change the path of the translation files
     fallbackLocale: const Locale('en', 'US'),
     child: const MyApp()),
);

With MyApp() being the root child, below is how we finalise the setup of the localisation inside our project.

class MyApp extends StatelessWidget {
 const MyApp({Key? key}) : super(key: key);

 // This widget is the root of your application.
 @override
 Widget build(BuildContext context) {

   return MaterialApp(
     localizationsDelegates: context.localizationDelegates,
     supportedLocales: context.supportedLocales,
     locale: context.locale,
     home: Center(
       child: Text("Welcome",
         style: TextStyle(
             fontSize: 13,
             color: Colors.black
         ),
       ),
     ),
   );
 }
}

As you will note, the root Widget of our application is a basic Text widget, which is wrapped inside a Center widget and contains some basic formatting. The hard-coded value of “Welcome” is also used for this part of the demonstration. This is where the magic begins. To access your translations, you can use some of the following commands:

Text('welcome').tr() //Text widget
print('welcome'.tr()); //String
var title = tr('welcome') //Static function

Basic translation

If we run the application in its current state, it will display the hard-coded “Welcome” text as seen in the screenshot below.

Now we can change Text(“Welcome”) to Text(“welcome”).tr() to take advantage of the localisation functionality we have added to our application in the previous steps. Note that the key “welcome” is lowercase, as it is associated with the key contained inside the en-US.json language file. If we reload our application with the above update applied and change the device language to Spanish, we will have a fully translated welcome message displayed in Spanish, according to what we have defined in our es-ES.json language file.

Advanced translation extension methods

After playing around with some utility methods in Flutter, we have written a few quick extensions to make life a little easier. Feel free to use them and write more of your own!

extension StringValidations on String {
 String get trCapitalCase => tr(this).capitalize ?? tr(this);
 String get trLowerCase => tr(this).toLowerCase();
 String get trCapsFirst =>
     '${tr(this)[0].toUpperCase()}${tr(this).substring(1)}';
 String get trUpperCase => tr(this).toUpperCase();
 String trParameter(String param, String value) {
   return replaceAll(param, value);
 }
}

Solution overview

This is a quick insight into how easily and effectively international language support can be added to a Flutter application, which will enable you to reach a greater global audience. This is just the tip of the iceberg – there are so many more benefits that can be had.

Jacques Fourie

RW Liebenberg

Lead Mobile Developer

Swipe iX Newsletter

Subscribe to our email newsletter for useful tips and valuable resources, sent out monthly.