Welcome to Our Website

Localization in Flutter App

Supporting multiple languages is the best practice to connect with a large section of audiences. Let’s dive in detail to get your flutter app to support multiple languages.

Introduction:

Flutter provides widgets and classes that help to have localization support for the app.

Flutter provides a flutter_localizations package dependency which is used to set up a localization. This package provides delegate methods that are being called when device language is changed. Apart from this package, we need to create local JSON files containing the key value pair for language translations.

Let’s take an example we will support two languages English and Deutsch.

Spet 1: Create language JSON files as an asset of the project:

For the English language create an “en.json” file and for Deutsch (German) language create a “de.json” file. Both of these JSON files contain key names and respective language-specific values of those keys.

en.json

{
    “welcome_text”:“Hello, Welcome to my blog”,
    “first_text”:“This is App localization example”
}

de.json

{
    “welcome_text”:”Hallo, Willkommen in meinem Blog”,
    “first_text”:“Dies ist ein Beispiel für die App-Lokalisierung”
}

2. Add dependencies:

pubspec.yaml

Let’s add “flutter_localizations” package dependencies in pubspec.yaml file.

dependencies:
flutter:
    sdk: flutter
flutter_localizations:latest_version 
    sdk: flutter

# To add assets to your application, add an assets section, like this:
assets:
- resources/language/de.json
- resources/language/en.json

3. Add localization for MaterialApp:

In order to apply localization in your application, you need to add supportLocales, localizationsDelegates as well as localeResolutionCallback in the MaterialApp widget which created in main.dart file.

3.1 Add suportLocales in MaterialApp:

supportedLocales: This property is used to set supported languages locally. By default, it will consider Americal English language.

Locale :

  • This class is used to select language and formatting of user’s language preferences.
  • Locale class contains languageCode, scriptCode, countyCode.

Locale class constructor:

  • Locale(String _languageCode,[String _countryCode]) Here, the first argument is required to define Locale in MaterialApp which is language code and the second argument is option which is county code.

Locale can be defined in application like,

  • const Locale(‘en’) => select language file on the bases of only language Code,
  • [const Locale(‘en’, ‘US’)] => select app language on the bases of language code as well as country code. Here, ‘en’ is the language code and ‘US’ is a country code.
supportedLocales: [
    Locale( 'en' , 'US' ),
    Locale( 'de' , 'DE' ),
],

3.2 Add localizationDelegates in MaterialApp widget:

localizationsDelegates is a list property in materialApp to get collection localized values from localize delegates.

GlobalMaterialLocalizations.delegate is used to get localized strings and other values for material components.

GlobalWidgetsLocalizations.delegate is used to define the default text direction for the widgets library.

localizationsDelegates: [
    ApplicationLocalizations.delegate,
    GlobalMaterialLocalizations.delegate,
    GlobalWidgetsLocalizations.delegate,
],

3.3 Add localResolutionCallback in MaterialApp widget:

localeResolutionCallback feature is used for fetch current language values from file as per country code and language code.

If the device’s current language code and country code is not matched to supported app language and country code then it will return data from that language which defines first in a sequence of supportLocales array or else it will return supported language file data.

localeResolutionCallback: (locale, supportedLocales) {
    for (var supportedLocaleLanguage in supportedLocales) {
        if (supportedLocaleLanguage.languageCode == locale.languageCode &&
                        supportedLocaleLanguage.countryCode == locale.countryCode) {
            return supportedLocaleLanguage;
        }
    }

    // If device not support with locale to get language code then default get first on from the list
    return supportedLocales.first;
}

In this code, if language local not supported then it will take english as default language for application and take values from the en.json file from the resource folder.

4. Create custom localization class:

Create application_localization.dart file under lib folder.

lib -> application_localizations.dart

Application localization class is created to get Locales from devices and user’s conditions for choosing language. On the bases of selected language, it will retrieve values from the assets JSON file and generate Map data as per JSON key-values pair.

application_localizations.dart

import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class ApplicationLocalizations {
 final Locale appLocale;

 ApplicationLocalizations(this.appLocale);

 static ApplicationLocalizations of(BuildContext context) {
   return Localizations.of<ApplicationLocalizations>(context, ApplicationLocalizations);
 }

 Map<String, String> _localizedStrings;

 Future<bool> load() async {
   // Load JSON file from the "language" folder
   String jsonString =
   await rootBundle.loadString('resources/language/${appLocale.languageCode}.json');
   Map<String, dynamic> jsonLanguageMap = json.decode(jsonString);
   _localizedStrings = jsonLanguageMap.map((key, value) {
     return MapEntry(key, value.toString());
   });
   return true;
 }

 // called from every widget which needs a localized text
 String translate(String jsonkey) {
   return _localizedStrings[jsonkey];
 }
}

In ApplicationLocalization class there are two main methods created :

1. load(): this method is used for loading JSON into Map<String, String>.

In load() method, JSON data comes from JSON file as per selected language JSON assets file and fetch key-values pair from that JSON.

2. translate(): is used for accessing the translated strings map data.

With translate() method, get value from language JSON file as per user-assigned key value in widget texts and strings.

Getting string value from JSON file

For getting String key-values from language json file, Call of() static method on ApplicationLocalizations() to get instance and fetch JSON values using translate() method.

Text(
    ApplicationLocalizations.of(context).translate('welcome_text'),
    textAlign: TextAlign.center,
),

Complete code is as follows :

main.dart

Here in main.dart file, materialApp widget will use for localizing your application with available language files in assets of project.

For localizing application, in MyApp() class, set supportLocales, localizationsDelegates, localeResolutionCallback for set application language as per device’s Locale’s country code and language code.

On the basis of language and country code app language will decide from ApplicationLocalizations.delegate and that selected language’s all key-values use in texts and strings in widgets throughout the app.

Impor t 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'application_localizations.dart';
import 'my_home_page.dart';

void main() => runApp( MyApp());

class MyApp extends StatefulWidget {
 @override
 State<StatefulWidget> createState() {
   return _MyAppState();
 }
}

class _MyAppState extends State<MyApp> {

 @override
 Widget build(BuildContext context) {
  return MaterialApp(
   title: 'Flutter Localization’,
   theme: ThemeData(
     primarySwatch: Colors.blue,
   ),
  // List all of the app's supported locales here
   supportedLocales: [
     Locale( 'en' , 'US' ),
     Locale( 'de' , 'DE' ),
   ],

    localizationsDelegates: [
     ApplicationLocalizations.delegate,
     GlobalMaterialLocalizations.delegate,
     GlobalWidgetsLocalizations.delegate,
   ],

   localeResolutionCallback: (locale, supportedLocales) {
        for (var supportedLocaleLanguage in supportedLocales) {
           if (supportedLocaleLanguage.languageCode == locale.languageCode &&
                            supportedLocaleLanguage.countryCode == locale.countryCode) {
                return supportedLocaleLanguage;
           }
       }
         return supportedLocales.first;
     },
        home: MyHomePage(),
    );
 }
}

myHomePage.dart

In HomePage() class, it sets values in widget text and strings using keys of JSON file of language.

import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'application_localizations.dart';

class MyHomePage extends StatefulWidget {

 @override
 State<StatefulWidget> createState() {
   return _MyHomePageState();
 }
}

class _MyHomePageState extends State<MyHomePage> {

 @override
 Widget build(BuildContext context) {
   return Scaffold(
     body: Center(
       child: Column(
           children: <Widget>[
             Text(
               ApplicationLocalizations.of(context).translate('welcome_text'),
               textAlign: TextAlign.center 
            ),
         Text(
               ApplicationLocalizations.of(context).translate('first_text'),
               textAlign: TextAlign.center 
             ),
           ],
         ),
     ),
   );
 }

Conclusion:

In this article, I have explained Localization / Multi-Language In Flutter, which you can modify and experiment with according to your own, this little introduction was from the Localization. In the Flutter demo from our side.

I hope this blog will provide you with sufficient information in Trying up the Localization In Flutter. In Flutter in your future project.