Flutter – Internationalization using easy_localization package

  • While developing your mobile app, you do care about users of the app and to provide better user experience, you can think about providing internationalization in the app i.e. having an option to switch between languages. Because users will love to see your app in their native languages, rather than keeping it limited to English.
  • There is easy_localization package in Flutter, that helps you achieve this, and provides lots of configuration options.
  • In this article, we will see how to use this package to create an app, where you can easily switch between languages – English and Hindi.

1. Add easy_localization dependency to your pubspec.yaml file.

dependencies:   
  easy_localization: <last_version>

2. Basic idea behind this package is, whenever you want to display some text on the screen, you will provide some key. Now this key will be defined in your both English and Hindi configuration files, with the value for the actual text required in that language against that key.
This package supports many file formats for keeping language configuration. In this article, we will see the most straightforward way – using json format. So let us create assets directory and in that create translations directory. Finally create 2 json files – en-US.json for English and hi-IN.json for hindi translations.

assets 
└── translations     
    ├── en-US.json
    └── hi-IN.json
en-US.json
{
  "message":"I am in love with {}"
}
hi-IN.json
{
  "message":"मुझे {} से प्यार है"
}

Here, {} in the value is a placeholder for argument that you can pass at the runtime.

3. For ios, you need to add supported locales to ios/Runner/Info.plist file.

<key>CFBundleLocalizations</key> 
<array> 
    <string>en</string> 
    <string>hi</string> 
</array>

4. Now inside your main.dart file, you need to wrap your MyApp() with EasyLocalization() widget, and pass the supportedLocales, path to the json files and other configuration required like follows:

void main() {
  runApp(
    EasyLocalization(
      supportedLocales: [Locale('en', 'US'), Locale('hi', 'IN')],
      path: 'assets/translations',
      fallbackLocale: Locale('en', 'US'),
      child: MyApp(),
    ),
  );
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      localizationsDelegates: context.localizationDelegates,
      supportedLocales: context.supportedLocales,
      locale: context.locale,
      title: 'Flutter Internationalization Demo',
      theme: ThemeData(
        primarySwatch: Colors.red,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: Home(),
    );
  }
}

5. Now wherever you want to use the actual message, you can use tr() extension function on the normal Text() widget for translations using the key, that will be there in your configuration jsons.

Text(
  'message',
  style: TextStyle(
    fontSize: 18,
  ),
).tr(args: ['Flutter']),

6. You can use extension methods to access/ change user locales like follows:

context.locale = Locale('hi', 'HI');

7. Stitching everything together:

import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
class Home extends StatefulWidget {
@override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
bool isHindi = false;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter Internationalization'),
),
body: SafeArea(
child: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Image.asset(
isHindi ? 'icons/flags/png/in.png' : 'icons/flags/png/us.png',
package: 'country_icons',
fit: BoxFit.cover,
),
SizedBox(
height: 25,
),
Text(
'message',
style: TextStyle(
fontSize: 18,
),
).tr(args: ['Flutter']),
SizedBox(
height: 20,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('Switch to Hindi?'),
Switch(
value: isHindi,
onChanged: (value) {
setState(() {
// this.setState is important here to change the locale!
this.setState(() {
if (value) {
context.locale = Locale('hi', 'IN');
} else {
context.locale = Locale('en', 'US');
}
});
isHindi = value;
});
},
activeTrackColor: Colors.redAccent,
activeColor: Colors.red,
),
],
),
],
),
),
),
);
}
}
view raw home.dart hosted with ❤ by GitHub

As you can see in the screenshot, we are able to achieve showing language specific text, without writing any conditions. Rather these texts are coming from the configuration json files, and they are loosely coupled with the application logic.

Complete source can be found on Github: https://github.com/Amitbhave/flutter-tutorials/tree/master/flutter_internationalization.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s