Providing Multi-Language Support in Flutter
Easy localization is a package used in Flutter to provide multi-language support. This package offers an easy method to localize your application in different languages. In this guide, I will explain how to achieve multi-language support in your Flutter application using the Easy localization package, along with code examples.
Step 1: Add the easy_localization package to your project dependencies. In the dependencies section of your pubspec.yaml file, add the following line:
dependencies:
flutter:
sdk: flutter
easy_localization: ^3.0.0
Step 2: Initialize the easy_localization package in your main.dart file. Wrap the MaterialApp widget’s home property with the EasyLocalization widget and specify the supported locales and the path to the language files.
import 'package:flutter/material.dart';
import 'package:easy_localization/easy_localization.dart';
void main() {
runApp(
EasyLocalization(
supportedLocales: [Locale('en', 'US'), Locale('tr', 'TR')],
path: 'assets/translations', // Path to the language files
fallbackLocale: Locale('en', 'US'), // Default language
child: MyApp(),
),
);
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomeScreen(),
localizationsDelegates: context.localizationDelegates,
supportedLocales: context.supportedLocales,
locale: context.locale,
);
}
}
Step 3: Create a folder named “translations” under the assets directory and create separate files for each language. For example, en.json and tr.json. These files will store the text and translations.
{
"greeting": "Hello, world!",
"title": "Easy Localization Guide in Flutter"
}
Step 4: Access the context.locale to change the language within the app and localize the text.
class HomeScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('title'.tr()), // Localize the text
),
body: Center(
child: Text('greeting'.tr()), // Localize the text
),
);
}
}
By following these steps, you can integrate the Easy localization package into your Flutter application and provide multi-language support. This allows your users to use your application in different languages, expanding its reach to a wider audience.
Enabling multi-language support with the Easy localization package enhances the user experience and enables you to share your application with a broader user base.