Localization in Flutter

Most of the apps are available in the English language. But what about the people who do not speak English. One of the common misconception these days is that most of the people who have access to the internet speak and understand the English language. Let us see what the statistics have to say. Only roughly 25% of the people speak English. Meaning, you might be missing 75% of your market by making your app just in the English language.

App localization can solve this problem. App localization is the process of changing the app to appeal to a geographically specific or linguistically specific target market. A principal part of localization includes translating the language.

Here, in this tutorial, we will learn how to do simple app localization in Flutter.

Install flutter_localization package

The first step of app localization is to add the flutter_localization package in pubspec.yaml under the dependencies shown above. Run flutter pub get to install the package.

Create language files

Create a new directory lang in the project’s root directory. You can create a JSON file for each language for which you plan to localize your app. For this tutorial, we will be localizing the app for English and Spanish. So, we have two files, “en.json” and “es.json” inside the lang folder.

The example JSON files are:

en.json

es.json

Add language files to pubspec.yaml

Make language files available by adding them under the assets of the pubspec.yaml showed above.

Create localization delegate

Create a file app_localizations.dart inside the lib folder shown in the image below.

In the app_localizations.dart file, first, define app localization delegate as a private class (_AppLocalizationsDelegate). It extends LocalizationsDelegate< AppLocalizations>. To access the localization delegate, we have created a static variable named delegate inside the AppLocalizations class. AppLocalizations class also contains a method load() to load the language JSON string as a Map< String, String>.

We call the translate function from the widget with the key and context to get a localized text.

Localize Material App

Initialize the localization objects in the material app shown above. The properties initialized for localization to work are supportedLocales, localizationsDelegates, and localeResolutionCallback. supportedLocales specify which languages are supported. localizationsDelegates specify the delegates. localeResolutionCallback returns the first locale defined in supportedLocales if the value of “locale” is null or is not in the supportedLocales list. If the “locale” is present in the supportedLocales list, it returns that particular locale.

Translate text in UI

To get a localized text, call the translate function with key and context.

Full Implementation

The full implementation is available in the GitHub link given below.

GitHub GITHUB

Scroll to Top