Localize Flutter Application: flutter_localization Package Guide

Haris Bin Nasir Avatar

·

·

In today’s tutorial, we’ll explore how to implement localization in a Flutter app. Localization allows your app to support multiple languages, making it accessible to a global audience. We’ll guide you through the setup process, configuring supported locales, and creating a user interface that adapts to different languages.

Once you have your Flutter environment ready, follow along as we build a localized Flutter app step by step.

If you prefer watching a video tutorial here is a link to that.

Adding the Localization Dependency

To handle localization in our Flutter app, add the following dependency to the pubspec.yaml file:

dependencies:
  flutter:
    sdk: flutter
  flutter_localization: ^0.2.1
  • flutter_localization:
    This package provides the tools necessary to implement localization in Flutter apps. It allows for easy management and switching between multiple languages. To get the dependency, click here.

Setting Up the Supported Locales

The first step in implementing localization is defining the locales that your app will support. We’ll create a file called locales.dart in consts folder to store these definitions.

Defining Locale Data

In locales.dart, we define the strings that will be translated into different languages.

import 'package:flutter_localization/flutter_localization.dart';

const List<MapLocale> LOCALES = [
  MapLocale("en", LocaleData.EN),
  MapLocale("de", LocaleData.DE),
  MapLocale("zh", LocaleData.ZH),
];

mixin LocaleData {
  static const String title = 'title';
  static const String body = 'body';

  static const Map<String, dynamic> EN = {
    title: 'Localization',
    body: 'Welcome to this localized Flutter application %a'
  };

  static const Map<String, dynamic> DE = {
    title: 'Lokalisierung',
    body: 'Willkommen bei dieser lokalisierten Flutter-Anwendung %a'
  };

  static const Map<String, dynamic> ZH = {
    title: '本土化',
    body: '欢迎使用这个本地化的 Flutter 应用程序 %a'
  };
}

This file contains translations for English, German, and Chinese. The %a in the body string is a placeholder that we will replace dynamically.

Configuring Localization in the Main Application File

Next, we need to configure localization in our main application file. This setup ensures that the app can handle multiple languages and switch between them smoothly.

Initializing Localization

First, we’ll initialize localization in the MyApp class.

import 'package:flutter/material.dart';
import 'package:flutter_localization/flutter_localization.dart';
import 'package:localization_app/localization/locales.dart';
import 'package:localization_app/pages/home_page.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final FlutterLocalization localization = FlutterLocalization.instance;

  @override
  void initState() {
    configureLocalization();
    super.initState();
  }

In this code:

  • FlutterLocalization initializes the localization instance.
  • configureLocalization() is a method we’ll define to configure supported locales.

Configuring Supported Locales

We need to define the configureLocalization() method, which sets up the supported locales.

void configureLocalization() {
  localization.init(mapLocales: LOCALES, initLanguageCode: "en");
  localization.onTranslatedLanguage = onTranslatedLanguage;
}

This method initializes the localization with the supported locales and sets the default language to English.

Updating the UI on Language Change

The onTranslatedLanguage() method ensures that the app’s UI updates whenever the user changes the language.

void onTranslatedLanguage(Locale? locale) {
  setState(() {});
}

Building the User Interface

Now, let’s build the user interface where users can select a language and see the localized content.

Creating the Home Page

We’ll start by creating the basic structure of the home page in home_page.dart.

import 'package:flutter/material.dart';
import 'package:flutter_localization/flutter_localization.dart';
import 'package:localization_app/localization/locales.dart';

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

Adding a Language Selection Dropdown

Next, we’ll add a dropdown menu in the AppBar to allow users to select their preferred language.

class _HomePageState extends State<HomePage> {
  late FlutterLocalization _flutterLocalization;
  late String _currentLocale;

  @override
  void initState() {
    super.initState();
    _flutterLocalization = FlutterLocalization.instance;
    _currentLocale = _flutterLocalization.currentLocale!.languageCode;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          LocaleData.title.getString(context),
        ),
        actions: [
          DropdownButton(
            value: _currentLocale,
            items: const [
              DropdownMenuItem(
                value: "en",
                child: Text("English"),
              ),
              DropdownMenuItem(
                value: "de",
                child: Text("German"),
              ),
              DropdownMenuItem(
                value: "zh",
                child: Text("Chinese"),
              ),
            ],
            onChanged: (value) {
              _setLocale(value);
            },
          )
        ],
      ),

Displaying Localized Content

Finally, we’ll display the localized content on the home page.

      body: Container(
        padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 50),
        child: Text(
          context.formatString(LocaleData.body, ["Hussain"]),
          style: const TextStyle(fontSize: 21),
        ),
      ),
    );
  }

  void _setLocale(String? value) {
    if (value == null) return;
    if (value == "en") {
      _flutterLocalization.translate("en");
    } else if (value == "de") {
      _flutterLocalization.translate("de");
    } else if (value == "zh") {
      _flutterLocalization.translate("zh");
    } else {
      return;
    }
    setState(() {
      _currentLocale = value;
    });
  }
}

In this UI:

  • Dropdown for Language Selection: A dropdown menu is provided in the AppBar, allowing users to select their preferred language.
  • Localized Content: The text widget displays content based on the selected language.

Running the Application

With everything set up, you can now run your application. This step will bring all the configurations together and allow you to test the multilingual functionality.

flutter run

You should now see a Flutter app that allows you to switch between English, German, and Chinese, displaying the content accordingly.

Get Source Code for free:

Conclusion

In this blog post, we learned how to implement localization in a Flutter app. This included setting up locales, configuring the app to support multiple languages, and building a user interface that dynamically updates based on the selected language. Localization is a key aspect of creating a global app that caters to users from different regions.

If you found this tutorial helpful, be sure to check out more Flutter tutorials on my blog!

Happy Coding…!!!

Leave a Reply

Your email address will not be published. Required fields are marked *