Developing Multi-Language Apps with Flutter

0

In the rapidly expanding field of mobile app development, it’s crucial to cater to a variety of users. The need for multilingual support in mobile apps has increased dramatically with the expansion of international business. For that reason, mobile and web app developers are continually looking for fresh and effective approaches to creating multilingual applications.

Let’s talk about the well-known open-source mobile app development framework – Flutter.

For startups looking to create feature-rich mobile apps without spending a fortune, Flutter may be the ideal framework. Here are the reasons that prove Flutter as the ideal choice for mobile app development.

Flutter is a UI toolkit that enables developers to create high-performing, high-fidelity apps from a single codebase for iOS, Android, and the web. It is well known for its quick development cycle and stunning, expressive user interface. But Flutter’s multi-language support is what makes it stand out from the other app development frameworks.

This article will cover various aspects that revolve around the development of a multi-language app using Flutter app development services. It will include the approach, procedure, and a few tips to make the more effortless.

Approach to multi-language app development

Developing multi-language apps is no easy task, but with Flutter, the process is a lot simpler. In this article, we’ll take a look at how you can use Flutter to create multi-language apps that are easy to use and maintain.

Internationalizing Your App

Firstly, internationalizing the code is crucial if you’re creating a multilingual app. This involves separating all of your app’s hardcoded text into a separate file and assuring that it is simple to translate. With the use of the Dart intl library, this procedure—known as “localization” in Flutter—is made simple.

To format and parse dates, times, and numbers as well as to create and display strings in many languages, use the Dart intl package. This package enables you to define messages in a single location, retrieve the right message for each locale, and display it.

Supporting Multiple Languages

The next stage is to add support for multiple languages after your app has been internationalized. For each language you want to support in Flutter, you may accomplish this by making a new localization. There are a number of messages that have been translated into each localization’s chosen language.

The program loads the proper localization after determining the device’s locale upon startup. Text is then shown in the app using the messages from the localization. As a result, the app will automatically show the right text in each language, and you only need to maintain one set of code.

Maintaining and Updating Localizations

You might need to add new messages, change old messages, or add support for new languages as you add new features to your app. It’s simple to update and manage localizations in Flutter. Without having to modify the code, add new messages to the localizations, update those that already exist, and add support for additional languages.

You may easily update the localizations with the most recent messages and translations when you’re prepared to release a new version of your app. As your company expands, this makes it simple to maintain and upgrade that multilingual app.

Check out the most recent uses cases of Flutter as a framework for App development.

Steps to develop a multi-language app with Flutter

Let’s cover the steps to develop a multi-language app with Flutter, including installation, asset setup, initial setup, basic translation, and advanced translation extension methods.

Installation

To get started with developing multi-language apps with Flutter, you first need to install Flutter on your system. You can download the latest version of Flutter from the official website. Once you have downloaded the installation package, follow the installation instructions for your platform.

After installing Flutter, you need to set up your development environment. You can use any code editor of your choice, such as Visual Studio Code or Android Studio. Make sure to install the Flutter and Dart plugins in your code editor.

Asset Setup

To add multi-language support to your app, you need to create a separate file for each language you want to support. These files are called localization files, and they contain the translations of your app’s text in each language.

To create the localization files, you need to create a folder named ‘i18n’ (short for internationalization) in the root directory of your project. Inside the ‘i18n’ folder, create a separate folder for each language you want to support. For example, if you want to support English and Spanish, create two folders named ‘en’ and ‘es’.

Inside each language folder, create a file named ‘strings.json’. This file will contain the translations for your app’s text in that language. The structure of the ‘strings.json’ file should be as follows:

{

    “key1”: “value1”,

    “key2”: “value2”,

    “key3”: “value3”

}

Where key1, key2, and key3 are the keys for the translations, and value1, value2, and value3 are the translated strings.

Initial Setup

Once you are done setting up the the locatlzation files, you need to initialize the Flutter app to use those files. In order to do this, you need to add the ‘flutter_localizations’ package to your app’s dependencies in the ‘pubspec.yaml’ file. It can be done by adding the following lines:

dependencies:

  flutter:

    sdk: flutter

  flutter_localizations:

    sdk: flutter

After adding the package, you need to import it in your main.dart file:

import ‘package:flutter_localizations/flutter_localizations.dart’;

You also need to add the ‘LocalizationsDelegate’ and ‘GlobalMaterialLocalizations’ classes to your app’s ‘localizationsDelegates’ property in the ‘MaterialApp’ widget. The ‘LocalizationsDelegate’ class is responsible for loading the translations from the localization files, and the ‘GlobalMaterialLocalizations’ class provides translations for common material design widgets.

class MyApp extends StatelessWidget {

  @override

  Widget build(BuildContext context) {

    return MaterialApp(

      localizationsDelegates: [

        GlobalMaterialLocalizations.delegate,

        GlobalWidgetsLocalizations.delegate,

        AppLocalizations.delegate,

      ],

      supportedLocales: [

        const Locale(‘en’),

        const Locale(‘es’),

      ],

      title: ‘MyApp’,

      home: MyHomePage(),

    );

  }

}

The “AppLocalizations.delegate” has been added to the “localizationsDelegates” property in the code above. This class is in charge of loading the translations from the earlier generated localization files.

To provide the list of languages that are required to support, ‘supportedLocales’ parameter is included. In this case, additional support is offered for both English and Spanish.

Basic Translation

Now that localization files have been set up and initialized the Flutter app to use them, you can start translating the text in the app.

To translate the text, you need to create a class that extends the ‘Translations’ class from the ‘flutter_localizations’ package. This class will provide the translations for your app’s text in each language.

import ‘dart:async’ show Future;

import ‘package:flutter/material.dart’;

import ‘package:flutter/services.dart’ show rootBundle;

import ‘dart:convert’;

class AppLocalizations {

  static AppLocalizations instance;

  Map<String, String> _localizedStrings;

  static Future<AppLocalizations> load(Locale locale) async {

    final AppLocalizations instance = AppLocalizations();

    final String jsonString = await rootBundle.loadString(‘i18n/${locale.languageCode}/strings.json’);

    final Map<String, dynamic> jsonMap = json.decode(jsonString);

    instance._localizedStrings = jsonMap.map((key, value) {

      return MapEntry(key, value.toString());

    });

    return instance;

  }

  static AppLocalizations of(BuildContext context) {

    return Localizations.of<AppLocalizations>(context, AppLocalizations);

  }

  String translate(String key) {

    return _localizedStrings[key];

  }

}

In the above code, a class named ‘AppLocalizations’ is created that extends the ‘Translations’ class. The ‘load’ method is responsible for loading the translations from the ‘strings.json’ file in the appropriate language folder. The ‘translate’ method is responsible for returning the translated string for a given key.

To use the ‘AppLocalizations’ class, you need to wrap your app in a ‘Localizations’ widget and specify the ‘AppLocalizations.delegate’ in the ‘delegates’ property. You can then use the ‘translate’ method to translate the text in your app.

class MyHomePage extends StatelessWidget {

  @override

  Widget build(BuildContext context) {

    return Scaffold(

      appBar: AppBar(

        title: Text(AppLocalizations.of(context).translate(‘app_title’)),

      ),

      body: Center(

        child: Text(AppLocalizations.of(context).translate(‘hello_world’)),

      ),

    );

  }

}

In the above code, the ‘translate’ method is used in order to translate the title of the app and the ‘hello world’ text.

Advanced Translation Extension Methods

In addition to the basic translation methods that are covered earlier, Flutter also provides some advanced translation extension methods that make it easier to translate text in certain scenarios.

trPlural: String trPlural(String key, int value) => tr(key, args: [value])

trFormatted: String trFormatted(String key, List<dynamic> args) => tr(key, args: args)

trOptional: String trOptional(String key) => tr(key, ifNotFound: key)

trFallback: String trFallback(String key, String fallbackKey) => tr(key, fallbackKey: fallbackKey)

trNested: String trNested(String key, Map<String, dynamic> values) => tr(key, namedArgs: values)

trWithDefault: String trWithDefault(String key, String defaultValue) => tr(key, ifNotFound: defaultValue)

trPluralWithNamedArgs: String trPluralWithNamedArgs(String key, int value, Map<String, dynamic> values) => tr(key, namedArgs: {‘value’: value, …values})

trUpper: String get trUpper => tr(this).toUpperCase()

trLower: String get trLower => tr(this).toLowerCase()

trTitleCase: String get trTitleCase => tr(this).titleCase()

Take into consideration that some of these extensions have extra requirements, such as the “intl” package for “trTitleCase”.

Conclusion

As it turns out that developing multi-language apps with Flutter is relatively easy thanks to its built-in localization support. In this article, we covered the basics of setting up localization in Flutter, including installation, asset setup, and initial setup. Lastly, some extension methods are discussed to make translation-related tasks a little easier.

Summing up, it was a quick sneak peek into the process of incorporating multiple languages into the Flutter application. By following the steps outlined in this article, mobile app development company can now easily develop multi-language apps that will appeal to a wider audience. This will ensure that the app reaches in the global market. There are countless additional advantages that can be attained; this is merely the tip of the iceberg. 

So, If you’re ready to take your app to the next level, reach out to DianApps today. Being one of the reputed mobile app development companies, they have a pool of resources and expertise to render the best flutter app development services. The expert flutter app developers are ready to help make your vision a reality, and together, you can turn your app idea into a success story. 

Article Source: https://medium.com/@DianApps/developing-multi-language-apps-with-flutter-4c44dbee7f41

Leave a Reply

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