Flutter Localization

A portrait painting style image of a pirate holding an iPhone.

by The Captain

on
May 22, 2023

Flutter Internationalization (i18n) and Localization

Flutter is an efficient and flexible development framework that allows you to build intuitive and interactive applications with ease. One important aspect of any mobile application is the ability to support multiple languages and regions. Flutter Internationalization (i18n) and Localization makes it possible to translate your application into different languages and change the app's response according to the user's location or region.

Steps involved in Flutter i18n and Localization

Flutter i18n and Localization involves three major steps. They are:

1. Generate translation files

The first step is to generate the translation files. You can use third-party libraries like flutter_localizations to generate the translation files. Also, some plugins let you import the translation files from CSV or JSON files.

flutter pub add flutter_localizations}

2. Define the string keys

After generating the translation files, you'll have to define the string keys that you want to translate. We recommend giving a unique identifier to each message key that makes it easier to find the content you need to translate.

class AppLocalizations {
  static Map> _localizedValues = {    
    'en': {
      'title': 'Flutter i18n Demo',
      'subtitle': 'Localized App using Flutter',
      'introduction': 'Flutter is a mobile SDK for building efficient and easy-to-use applications for Android and iOS.',
    }, 
    'es': {
      'title': 'Demo i18n de Flutter',
      'subtitle': 'Aplicación localizada con Flutter',
      'introduction': 'Flutter es un SDK móvil para construir aplicaciones eficientes y fáciles de usar para Android e iOS.',
    },
  };

  String? getLocalizedString(String key, {String? local}) {
    if (local == null || _localizedValues[local] == null || _localizedValues[local]![key] == null) {
      return _localizedValues['en']![key]; 
    }
    return _localizedValues[local]![key];
  }
}

3. Implement localization in Flutter

After defining the string keys, you can now start implementing the localization in your Flutter application. You can do this by creating a delegate that will help you manage the translations.

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

import 'app_localizations.dart';

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State {
  Locale? _locale;

  void setLocale(Locale value) {
    setState(() {
      _locale = value; 
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter I18n Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: HomePage(),
      locale: _locale,
      supportedLocales: [
        const Locale('en'),
        const Locale('es'),
      ],
      localizationsDelegates: [
        const AppLocalizationsDelegate(), 
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
      ],
    );
  }
}

class AppLocalizationsDelegate extends LocalizationsDelegate {
  const AppLocalizationsDelegate();

  @override
  bool isSupported(Locale locale) => ['en', 'es'].contains(locale.languageCode);

  @override
  Future load(Locale locale) async {
  Map>? localization = await AppLocalizations.loadJson(locale);

    AppLocalizations appLocalizations = new AppLocalizations();
    appLocalizations.localString = localization;

    return appLocalizations;
  }

  @override
  bool shouldReload(AppLocalizationsDelegate old) => false;
}

Conclusion

Flutter Internationalization (i18n) and Localization is an essential feature that enables you to offer your users an engaging user experience by redefining your app's response based on their language and region. With this tutorial, you can implement localization in your Flutter application effortlessly.