Implementing Localization in Flutter with GetX: A Simple Guide

Implementing Localization in Flutter with GetX: A Simple Guide

In today’s globalized world, developing apps that cater to users from different regions and speak different languages is essential. Flutter, with its vast set of packages and rich community, makes this task relatively easy. In this article, I’ll walk you through how to implement localization in Flutter using the powerful GetX package.

With Flutter, localization is relatively straightforward. Using packages like flutter_localizations and GetX, we can easily switch between different languages.

GitHub Repo

For the full code and a working example, check out the GitHub repository: GitHub Repository: flutter_tutorial

Steps to Implement Localization in Flutter

I’m going to demonstrate how you can implement localization in a Flutter project. Here’s the process I followed:

1. Install Required Dependencies

The first step is to add the necessary dependencies to your pubspec.yaml file. We’ll need the following packages:

  • get: A state management solution that simplifies various Flutter tasks, including localization.
  • flutter_localizations: Flutter’s official localization package.
  • shared_preferences: A package for storing data locally, used here to save the user's selected language.

name: flutter_tutorial
description: "Flutter Tutorial"
publish_to: 'none' # Remove this line if you wish to publish to pub.dev
version: 1.0.0+1

environment:
  sdk: ^3.5.3

dependencies:
  flutter:
    sdk: flutter
  flutter_localizations:
    sdk: flutter
  cupertino_icons: ^1.0.8
  get: ^4.6.6
  shared_preferences: 2.2.2

dev_dependencies:
  flutter_test:
    sdk: flutter
  flutter_lints: ^4.0.0

flutter:
  uses-material-design: true
  assets:
    - assets/localizations/        

2. Create Assets Folder for Localized Strings

Next, you need to create a folder to store your language-specific JSON files. Each language will have a corresponding .json file with its translations.

For example:

  • assets/localizations/en.json (English)
  • assets/localizations/es.json (Spanish)
  • assets/localizations/hi.json (Hindi)

The en.json file might look like this:

{
  "localizations_demo": "Localization Demo",
  "content_text": "This is a localized text"
}        

3. Set Up the Localization Service

Here, I created a LocalizationService class to load and manage translations. The LocalizationService will load the translation files and make them available throughout the app.

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'dart:convert';
import 'package:flutter/services.dart';
import 'package:shared_preferences/shared_preferences.dart';

class LocalizationService extends Translations {
  static final List<String> supportedLanguages = ["en", "hi", "zh", "fr", "es", "ar"]; 
  static const Locale fallbackLocale = Locale('en', 'US');
  static Locale defaultLocale = fallbackLocale;

  static final Map<String, Map<String, String>> _localizedStrings = {};

  static Locale createLocale(String language) {
    return language.contains('_')
        ? Locale.fromSubtags(
            languageCode: language.split('_').first,
            scriptCode: language.split('_').last,
          )
        : Locale(language);
  }

  List<Locale> getSupportedLocales() {
    return supportedLanguages.map((language) => createLocale(language)).toList();
  }

  static Future<void> loadTranslations() async {
    for (var locale in supportedLanguages) {
      String jsonString = await rootBundle.loadString('assets/localizations/$locale.json');
      Map<String, dynamic> jsonMap = json.decode(jsonString);
      _localizedStrings[locale] = jsonMap.map((key, value) => MapEntry(key, value.toString()));
    }
    defaultLocale = await getLocale();
  }

  @override
  Map<String, Map<String, String>> get keys => _localizedStrings;

  static void updateLocale(String locale) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setString('locale', locale); 
    Get.updateLocale(Locale(locale));
  }

  static Future<Locale> getLocale() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String? savedLocale = prefs.getString('locale');
    return createLocale(savedLocale ?? fallbackLocale.languageCode);
  }
}        

4. Set Up the Main Application Widget

In the main.dart file, we initialize the LocalizationService and load translations before starting the app. We also configure the GetMaterialApp widget to support multiple languages.

import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:get/get.dart';
import 'localization_service.dart';
import 'home.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await LocalizationService.loadTranslations();
  runApp(const MyApp());
}

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

  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      title: 'Localizations Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      locale: LocalizationService.defaultLocale,
      translations: LocalizationService(),
      supportedLocales: LocalizationService().getSupportedLocales(),
      localizationsDelegates: const [
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
      ],
      home: Home(),
    );
  }
}        

5. Create a Home Screen with Language Switching

In the Home screen, I’ve created a dropdown to let users select their preferred language. When a language is selected, the app updates the locale dynamically using the LocalizationService.

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'home_controller.dart';

class Home extends StatelessWidget {
  Home({super.key});

  final HomeController dropdownController = Get.put(HomeController());

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('localizations_demo'.tr),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: [
            Obx(() => DropdownButton<String>(
              value: dropdownController.selectedValue.value,
              items: dropdownController.items.map((item) => DropdownMenuItem<String>(
                value: item['key'],
                child: Text(item['value'] ?? ''),
              )).toList(),
              onChanged: (value) {
                if (value != null) dropdownController.setSelected(value);
              },
            )),
            Padding(
              padding: const EdgeInsets.all(10.0),
              child: Text('content_text'.tr),
            ),
          ],
        ),
      ),
    );
  }
}        

6. Test and Enjoy!

After following these steps, you’ll have a fully functional multilingual Flutter app that allows users to switch languages. The selected language is stored using SharedPreferences, so the app remembers the user’s choice even after it’s closed and reopened.

Conclusion

By following these simple steps, you’ll have a fully functional, multilingual app in no time. Flutter and GetX make it incredibly easy to localize your app, ensuring your users have a personalized experience in their preferred language.

Try it out and make your app accessible to a global audience! Happy coding!

To view or add a comment, sign in

More articles by Rohit Giri

Others also viewed

Explore content categories