Sobes.tech
Middle

How to add localization to a Flutter application?

sobes.tech AI

Answer from AI

  1. Adding dependencies:

    In the pubspec.yaml file, add dependencies for localization:

    dependencies:
      flutter:
        sdk: flutter
    
      flutter_localizations:
        sdk: flutter
      intl: ^0.18.0 # Example version, may vary
    

    Then run flutter pub get.

  2. Creating localization files:

    Create directories for localization resources, e.g., ./lib/l10n/. Inside, create .arb files for each supported language. For example, for English and Russian:

    app_en.arb:

    {
      "helloWorld": "Hello World!",
      "@@locale": "en"
    }
    

    app_ru.arb:

    {
      "helloWorld": "Привет мир!",
      "@@locale": "ru"
    }
    
  3. Configuring code generation:

    In the pubspec.yaml file, specify the path to localization files and configure .arb generation:

    flutter:
      generate: true # Enable generation
    
      assets:
        - assets/... # Your other assets
    
      l10n:
        arb-dir: lib/l10n # Directory with .arb files
        template-arb-file: app_en.arb # Template .arb file
        output-localization-file: app_localizations.dart # Name of generated file
    

    After saving pubspec.yaml, Flutter will automatically generate the file ./lib/generated/l10n.dart (or the specified output-localization-file).

  4. Using localized strings:

    In the app where you need to use localized strings, import the generated file:

    import 'package:flutter_gen/gen_l10n/app_localizations.dart';
    

    Then access the localized string via AppLocalizations.of(context)!:

    Text(AppLocalizations.of(context)!.helloWorld),
    
  5. Configuring MaterialApp or CupertinoApp:

    In the top-level widget (usually MaterialApp or CupertinoApp), specify language support and localization delegates:

    import 'package:flutter_gen/gen_l10n/app_localizations.dart';
    
    MaterialApp(
      // ... other settings
      localizationsDelegates: const [
        AppLocalizations.delegate, // Delegate from generated file
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
      ],
      supportedLocales: const [
        Locale('en', ''), // English
        Locale('ru', ''), // Russian
        // ... other supported languages
      ],
      // ...
    );
    

Now the app will automatically select localization based on the user's device settings if available in supportedLocales. To manually change the locale, you can use Locale and update the app state.