Open In App

Application Localization in Flutter

Last Updated : 08 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In mobile applications, Localization is the process of adapting an application to support multiple languages and regional settings. This allows your app to be more accessible to users from different parts of the world. In Flutter, for implementing Localization flutter_localization is a package used for in-app localization. It allows developers to create a single codebase that can display content in various languages, making the app accessible to a global audience. This is crucial for reaching users worldwide and providing a native experience regardless of their language preferences.

In this article, we'll explore how to implement localization in Flutter, making your app accessible to a global audience.

Prerequisites

  • Flutter SDK installed (version 2.0 or later)
  • Basic knowledge of Dart and Flutter development
  • A code editor (e.g., Visual Studio Code, Android Studio)

How to Implement App Localization in Flutter?

Here's a complete step-by-step guide on how to implement app localization in Flutter with an example project, changing languages from English to Spanish.

Step 1: Create a New Flutter Project

Create a new project with your project_name, In our case here it is geeksforgeeks_localization.

flutter create geeksforgeeks_localization
cd geeksforgeeks_localization

Step 2: Add Dependencies

Open the pubsec.yaml file and add the following dependencies required for the project.

dependencies:
flutter:
sdk: flutter
flutter_localizations:
sdk: flutter
intl: ^0.19.0

flutter:
generate: true

Run flutter pub get to fetch the dependencies.

Step 3: Creating Localization Files

Now, let's create the localization files for English and Spanish.

  • Create a new directory lib/l10n.
  • In this directory, create two files: app_en.arb and app_es.arb.

1. app_en.arb (English):

{
"appTitle": "GeeksforGeeks Localization",
"welcomeMessage": "Welcome to GeeksforGeeks!",
"languageSelection": "Select a language:",
"englishOption": "English",
"spanishOption": "Spanish"
}

2. app_es.arb(Spanish):

{
"appTitle": "Localización de GeeksforGeeks",
"welcomeMessage": "¡Bienvenido a GeeksforGeeks!",
"languageSelection": "Selecciona un idioma:",
"englishOption": "Inglés",
"spanishOption": "Español"
}

Step 4: Configuring the Main App

Let's set up our main app to use localization.

Replace the contents of lib/main.dart with:

main.dart
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
import 'home.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'GeeksforGeeks Localization',
      localizationsDelegates: [
        AppLocalizations.delegate,
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
      ],
      supportedLocales: [
        Locale('en', ''), // English
        Locale('es', ''), // Spanish
      ],
      home: Home(),
    );
  }
}


  • This code initializes a Flutter app that supports localization and also configures it for English and Spanish.
  • It then loads the necessary resources needed for localization and makes the Home widget the initial screen.
  • This application is able to load and show localized buttons or strings from my localizationsDelegates and supportedLocales based on user locale settings.

Step 5: Creating the Home Screen

Now, let's create a home screen that demonstrates localization in action.

Create a new file lib/home.dart:

home.dart
import 'package:flutter/material.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';

class Home extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final localizations = AppLocalizations.of(context)!;

    return Scaffold(
      appBar: AppBar(
        title: Text(localizations.appTitle),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              localizations.welcomeMessage,
              style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
            ),
            SizedBox(height: 20),
            Text(
              localizations.languageSelection,
              style: TextStyle(fontSize: 18),
            ),
            SizedBox(height: 10),
            ElevatedButton(
              onPressed: () => _changeLocale(context, Locale('en')),
              child: Text(localizations.englishOption),
            ),
            SizedBox(height: 10),
            ElevatedButton(
              onPressed: () => _changeLocale(context, Locale('es')),
              child: Text(localizations.spanishOption),
            ),
          ],
        ),
      ),
    );
  }

  void _changeLocale(BuildContext context, Locale newLocale) {
    Navigator.of(context).pushReplacement(
      MaterialPageRoute(
        builder: (BuildContext context) => Localizations.override(
          context: context,
          locale: newLocale,
          child: Home(),
        ),
      ),
    );
  }
}


Don't forget to import HomeScreen in main.dart

  • The Home widget shows localized text for different parts of the app such as title, welcome message, language selection options.
  • This app has been made in such a way that users can switch between English and Spanish languages without having to restart it every time they want to change language settings dynamically.
  • The _changeLocale method creates a new instance of this class with the current build context, ensuring that when it’s called again later on all changes will apply accordingly so as not only does our app reflect selected languages but also keeps sending important data back home even though we may lose those at some point in future due say an update by flutter itself or just normal software updates during which several recompilations take place especially if many libraries were updated along with their dependencies.

Step 6: Generating Localization Files

flutter gen-l10n

This command will generate the necessary Dart files for localization based on our ARB files.

Step 7: Running the App

flutter run

You should see an app with a welcome message and two buttons to switch between English and Spanish.

Output :


Next Article
Article Tags :

Similar Reads