Flutter Easy Localization – Adding Extra Efficiency to Flutter Apps

Today’s business prospects are not limited to one region only, and there are several ways these are achieved. If we convert these propositions to Mobile/Web Apps, we learn that adding multiple languages helps grow sales in a large number. That said, let’s have an in-depth conversation regarding Flutter Easy Localization – Adding Extra Efficiency to Flutter Apps.


Table of Contents

Internationalizing in Flutter App – A Quick Overview

By default, Flutter only supports US English Localization (l10n), but it is capable of supporting the rest too. Additionally, certain packages are either recommended by Flutter itself or some third party. However, our primary focus would be on Easy Localization throughout this blog post.

Easy Localization

This package is built to provide fast and effective internationalization for Flutter Apps. Moreover, it supports the following:

- Switching language optimizations
- supporting multiple format translation files
- Almost all languages are there
- Optimized with null-safety
- Customized error Widget screen in case of issues
- Capable of handling the default language in case of any issue
- Auto-optimized RTL & LTR Languages
- Saves the Locale, which was last used - No need for any Local Storage

Furthermore, the above list indicates that Easy Localization must be considered a developer’s first choice. So, let’s dive deep down toward the next section and start implementing it.

Package implementation

Firstly, mind map, how many languages there should be. For instance, taking English and Urdu respectively.

Project Scenario

For the sake of simplicity, let’s have an App that consists of text and a button (to trigger the language).

Installing the package

Head over to the project’s terminal and write this command:

flutter pub add easy_localization

——————- OR ——————

Install it manually, a suitable version according to you.

https://pub.dev/packages/easy_localization

Folder creation

In the project directory itself, create a new folder as assets. Furthermore, add a new directory named languages.

Inside this, create two separate files as .json extensions.

The language format should be as follows:

en-US.json
ur-PK.json

Note: Once we’re done, don’t forget to mark this path under pubspec.yaml.

Next, make some modifications to your existing code according to the structure defined above.

import 'package:flutter/material.dart';

class ElDemo extends StatefulWidget {
  const ElDemo({Key? key}) : super(key: key);

  @override
  State<ElDemo> createState() => _ElDemoState();
}

class _ElDemoState extends State<ElDemo> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 10),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [

            Text(
              "greetings".tr(),
              style: const TextStyle(
                fontSize: 14,
                fontWeight: FontWeight.w800,
                color: Color(0xff000000),
              ),
            ),

            ElevatedButton(
              onPressed: () {},
              child: const Text('Toggle'),
            ),
          ],
        ),
      ),
    );
  }
}

It’s time to fill up those JSON files that were left.

en-US.json

{
  "greetings": ""Good to see you. / It’s been ages! (since I’ve seen you.) 
  / Where have  you been hiding? / What have you been up to?"
}

Note: For the rest of the languages, you can make use of any third-party software or ask your client to provide it for you.

ur-PK.json

{
  "greetings": "آپ کو دیکھ کر اچھا لگا. / یہ کئی سال ہو گئے ہیں! (جب سے میں نے آپ کو دیکھا   
   ہے.) / تم کہاں چھپے ہوئے ہو؟ /تم کيا کر رہے ہو?"
}

Now, replace this text with:

/* OLD */
Text(
   greetings,
   style: TextStyle(
   fontSize: 14,
   fontWeight: FontWeight.w800,
   color: Color(0xff000000),
  ),   
),

/* NEW */
Text(
   greetings.tr(),
   style: TextStyle(
   fontSize: 14,
   fontWeight: FontWeight.w800,
   color: Color(0xff000000),
  ),   
),

It will prompt an error, just import the package URL, and we’re good to go.

A couple of changes to the root (main)

We have yet to finalize the changes needed for the plugin. So, let’s make some configurations for the main() and MaterialApp sections.

main()

Before runApp, add these files:

Note: We need to set this method to asynchronous.

WidgetsFlutterBinding.ensureInitialized();
await EasyLocalization.ensureInitialized();

vis-à-vis, wrap the Widget that has been part of runApp with EasyLocalization as follows:

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await EasyLocalization.ensureInitialized();
  runApp(
    EasyLocalization(
        supportedLocales: const [
          Locale('en', 'US'),
          Locale('ur', 'PK'),
        ],
        path: 'assets/languages',
        fallbackLocale: const Locale('en', 'US'),
        child: const MyApp()
    ),
  );
}

We’re done with this stuff.

MaterialApp

Add these lines inside the MaterialApp Widget

localizationsDelegates: context.localizationDelegates,
supportedLocales: context.supportedLocales,
locale: context.locale,

With this, our App is ready to be launched.

Running the App

Run the App on an emulator or real device, whichever suits you best.

If you’ve followed all the steps correctly, you should see the main screen without any issues.

Flutter Easy Localization - Output

Next, we need to link the onPressed event with the toggling language.

To change the language, we shall use the following extension:

context.setLocale(Locale('en', 'US'));

w.r.t each associated class’s context.

Furthermore, let’s add a condition to the Button event.

Column(
   mainAxisAlignment: MainAxisAlignment.center,
   children: [

     Text(
       "greetings".tr(),
        style: const TextStyle(
        fontSize: 14,
        fontWeight: FontWeight.w800,
        color: Color(0xff000000),
     ),
   ),

    ElevatedButton(
      onPressed: () {
        bool isEng = context.locale == const Locale('en', 'US');

         if(isEng) {
             context.setLocale(const Locale('ur', 'PK'));
           }
         else {
           context.setLocale(const Locale('en', 'US'));
         }
       },
      child: const Text('Toggle'),
     ),
   ],
  ),

Restart the App to reflect the changes well.

We should be able to see our desired output.

Another interesting thing about this package is that it is pre-built with SharedPreferences, and we don’t need any additional steps but one, i.e.

In the runApp method itself, add:

saveLocale: true,

/* Final Output
runApp(
    EasyLocalization(
        supportedLocales: const [
          Locale('en', 'US'),
          Locale('ur', 'PK'),
        ],
        path: 'assets/languages',
        saveLocale: true,
        fallbackLocale: const Locale('en', 'US'),
        child: const MyApp()
    ),
  );

And we’re good to go!

Moreover, there is also a great tutorial available on my YouTube channel as well.

It’s time to wrap up this blog post. However, I would love to hear your feedback about this one and the rest.

Thanks much for your precious time!

GOOD DAY!


Conclusion

In this insightful blog post titled “Flutter Easy Localization – Adding Extra Efficiency to Flutter Apps,” we delved into the comprehensive concept of Internationalization in Flutter, providing readers with a thorough understanding of its significance and implementation within Flutter applications.

Moreover, the blog post includes lots of code examples and snippets to help you understand Internationalization in Flutter. These examples are spread out in a way that makes it easy to learn how to integrate the above into your Flutter projects.

Continually, if you find something that has been missed out, or not spoken, please jot it down in the comments section below, I would be more than happy to respond timely.

P.S. Don’t forget to check out my GitHub Repositories, as there are tons of content available, so for my YouTube channel as well.

Secondly, read out my previous blogs – Click Here

Also, read Here’s Why You Should Use Flutter Hooks – An interesting concept

Leave a Comment