Multi-Language Localization in Flutter

Multi-Language Localization in Flutter

Localization is an essential aspect of mobile app development, allowing applications to support multiple languages and provide a better user experience for global audiences. In Flutter, localization is achieved using the flutter_localizations package, along with intl for managing multiple languages.

How Localization Works in Flutter

Flutter provides built-in support for internationalization (i18n) and localization (l10n) using the following steps:

1. Add Dependencies

To enable localization in your Flutter app, add the required dependencies to your pubspec.yaml file:

dependencies:
  flutter:
    sdk: flutter
  flutter_localizations:
    sdk: flutter
  intl: ^0.18.0        

2. Enable Localization Support

Modify your MaterialApp widget in main.dart to support multiple languages:

import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:intl/intl.dart';
import 'l10n/app_localizations.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      supportedLocales: [
        Locale('en', ''),
        Locale('es', ''),
        Locale('fr', ''),
      ],
      localizationsDelegates: [
        AppLocalizations.delegate,
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
      ],
      localeResolutionCallback: (locale, supportedLocales) {
        for (var supportedLocale in supportedLocales) {
          if (supportedLocale.languageCode == locale?.languageCode) {
            return supportedLocale;
          }
        }
        return supportedLocales.first;
      },
      home: HomeScreen(),
    );
  }
}        

3. Create Localization Files

Create a directory l10n/ inside your project and add JSON or ARB (Application Resource Bundle) files for different languages.

Example JSON File (l10n/en.json)

{
  "title": "Hello, World!",
  "greeting": "Welcome to Flutter Localization"
}        

Example JSON File (l10n/es.json)

{
  "title": "Hola, Mundo!",
  "greeting": "Bienvenido a la localización de Flutter"
}        

4. Implement a Localization Class

Create app_localizations.dart inside l10n/ to manage localized strings:

import 'dart:convert';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';

class AppLocalizations {
  final Locale locale;

  AppLocalizations(this.locale);
  
  static AppLocalizations? of(BuildContext context) {
    return Localizations.of<AppLocalizations>(context, AppLocalizations);
  }

  static const LocalizationsDelegate<AppLocalizations> delegate = _AppLocalizationsDelegate();

  Map<String, String> _localizedStrings = {};

  Future<void> load() async {
    String jsonString = await rootBundle.loadString('l10n/${locale.languageCode}.json');
    Map<String, dynamic> jsonMap = json.decode(jsonString);
    _localizedStrings = jsonMap.map((key, value) => MapEntry(key, value.toString()));
  }

  String translate(String key) {
    return _localizedStrings[key] ?? key;
  }
}

class _AppLocalizationsDelegate extends LocalizationsDelegate<AppLocalizations> {
  const _AppLocalizationsDelegate();

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

  @override
  Future<AppLocalizations> load(Locale locale) async {
    AppLocalizations localizations = AppLocalizations(locale);
    await localizations.load();
    return localizations;
  }

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

5. Using Localized Strings in Widgets

To display localized text, use:

Text(AppLocalizations.of(context)!.translate('title'))        

6. Switching Languages Dynamically

To change the language at runtime, update the locale of the MaterialApp dynamically by using setState.

void _changeLanguage(Locale locale) {
  setState(() {
    MyApp.of(context)!.setLocale(locale);
  });
}        

Conclusion

Multi-language localization in Flutter is a powerful feature that allows apps to cater to a global audience. By following these steps, you can easily integrate localization support and provide a seamless multilingual experience. For advanced localization, consider using flutter_translate or easy_localization packages.


要查看或添加评论,请登录

aishwarya mali的更多文章