Flutter Change App Language – Multi Languages – GetX Localization

Create a New Flutter Project or open Exisiting Project

Use your favorite IDE( Android Studio, VSCode or IntelliJS) to build Flutter App, Create a new Flutter Project.
I use Android Studio to build Flutter Application.

Install/Add Flutter GetX Dependencies

Open pubspec.yaml file & add getx Package under dependencies like this as shown below:dependencies: get: #any version

After adding the dependencies hit pub get button or run flutter pub get command in your IDE Terminal.

Now, you have successfully added getx package in your flutter, Now to make use of getx you need to import get.dart in flutter dart code to use it.import ‘package:get/get.dart’;

How to use GetX Flutter library to add multiple language in flutter app

Change root Widget ‘MaterialApp’ to ‘GetMaterialApp’

By using ‘GetMaterialApp’, you can pass 2 parameter i.e. locale & translations.

GetMaterialApp Properties

There are many properties(parameter) that can be used.
In this project example we will use locale &  translations.

  • locale: initial/default language translations of App.
  • translations: pass your translation class that contain translated strings of locales language.

Code

// This widget is the root of your application.
@override
Widget build(BuildContext context) {
  return GetMaterialApp(
    title: 'Flutter Demo',
    translations: AppTranslations(),
    locale: storage.lanCode!=null
          ?Locale(storage.lanCode!,storage.countryCode)
          :Locale("en","US"),
    fallbackLocale:Locale("en","US"),
    initialBinding: InitialBinding(),
    theme: ThemeData(
      primarySwatch: Colors.blue,
    ),
    home: const MyHomePage(title: 'Flutter Demo Home Page'),
  );
}
Dart

Create custom locale key-value translation class

Create a new Dart file, that extends Translations class.his class has Translations as key-value dictionary map language strings.Here we will define our locale language translated Strings.Code

import 'package:get/get.dart';

class AppTranslations extends Translations {
  @override
  // TODO: implement keys
  Map<String, Map<String, String>> get keys => {
    'en_US':{
      'hello':'Hello World',
      'welcome':"Welcome"
    },
    'de_DE':{
      'hello':'Hello Welt',
      'welcome':"willfommen"
    },
    'pt_BR':{
      'hello':'Alo Mundo',
      'welcome':"Bem-vindo"
    },
  };

}
Dart

How to use translations in flutter with Getx

You have defined your locale languages in translations class.

you can use the specified ‘key’ & just append with .tr & thus the locale language will be translated in your flutter app.Eg: Text('hello'.tr),

How to change app language in flutter – Change Locale

GetX Provide a function to change locale language

Code

void updateLocale(String key){
  final String languageCode=optionslocales[key]['languageCode'];
  final String countryCode=optionslocales[key]['countryCode'];
  Get.updateLocale(Locale(languageCode,countryCode));
  local.value=Get.locale.toString();
  storage.write("languageCode", languageCode);
  storage.write("countryCode", countryCode);
}
Dart

Full Code

main.dart

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:translatorflutter/AppTranslations.dart';
import 'package:translatorflutter/ChangeLan.dart';
import 'package:translatorflutter/InitialBinding.dart';
import 'package:translatorflutter/StorageService.dart';

var storage;
void main() async{

  WidgetsFlutterBinding.ensureInitialized();
  //init
  await initalConfig();
//initalize
   storage=Get.find<StorageService>();
  runApp( MyApp());
}

initalConfig()async {
  await Get.putAsync(() => StorageService().init());
}

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

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      title: 'Flutter Demo',
      translations: AppTranslations(),
      locale: storage.lanCode!=null
            ?Locale(storage.lanCode!,storage.countryCode)
            :Locale("en","US"),
      fallbackLocale:Locale("en","US"),
      initialBinding: InitialBinding(),
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      // This call to setState tells the Flutter framework that something has
      // changed in this State, which causes it to rerun the build method below
      // so that the display can reflect the updated values. If we changed
      // _counter without calling setState(), then the build method would not be
      // called again, and so nothing would appear to happen.
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
   return Scaffold(
     appBar: AppBar(),
     body: Center(child: Container(
       child: Column(
         children: [
           SizedBox(height: 100,),
           Text("hello".tr),
           Text("welcome".tr),
       LanguageMenu()
         ],
       ),
     )),
   );
  }

}
Dart

StorageService.dart

import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';

class StorageService extends GetxService{
  String? lanCode;
  String? countryCode;

  Future<StorageService> init()async{
    await GetStorage.init();
    lanCode=await GetStorage().read('languageCode');
    countryCode=await GetStorage().read('countryCode');
    return this;
  }
  void write(String key,String value){
    GetStorage().write(key,value);
  }


}

Dart

InitialBinding.dart

import 'package:get/get.dart';
import 'package:translatorflutter/LanguageController.dart';

class InitialBinding extends Bindings{
  @override
  void dependencies() {
    //see we create this one
  Get.put(LanguageController(),permanent:true);
  }

}
Dart

AppTranslations.dart

import 'package:get/get.dart';

class AppTranslations extends Translations {
  @override
  // TODO: implement keys
  Map<String, Map<String, String>> get keys => {
    'en_US':{
      'hello':'Hello World',
      'welcome':"Welcome"
    },
    'de_DE':{
      'hello':'Hello Welt',
      'welcome':"willfommen"
    },
    'pt_BR':{
      'hello':'Alo Mundo',
      'welcome':"Bem-vindo"
    },
  };

}
Dart

LanguageController.dart

import 'dart:ui';

import 'package:get/get.dart';
import 'package:translatorflutter/StorageService.dart';

class LanguageController extends GetxController{
  final storage=Get.find<StorageService>();
  final RxString local=Get.locale.toString().obs;


  final Map<String,dynamic> optionslocales={
    'en_US':{
      'languageCode':'en',
      'countryCode':'US',
      'description':'English',
    },
    'de_DE':{
      'languageCode':'de',
      'countryCode':'DE',
      'description':'German',
    },
    'pt_BR':{
      'languageCode':'pt',
      'countryCode':'BR',
      'description':'Portugues',
    },
  };

  void updateLocale(String key){
    final String languageCode=optionslocales[key]['languageCode'];
    final String countryCode=optionslocales[key]['countryCode'];
    Get.updateLocale(Locale(languageCode,countryCode));
    local.value=Get.locale.toString();
    storage.write("languageCode", languageCode);
    storage.write("countryCode", countryCode);
  }

}

Dart

LanguageMenu.dart

import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:get/get.dart';
import 'package:translatorflutter/LanguageController.dart';

class LanguageMenu extends GetView<LanguageController>{
  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: null,
      child: PopupMenuButton(
        icon: Icon(Icons.language),
        offset: Offset(0,30),
        itemBuilder: (context)=>controller.optionslocales.entries.map((e){
          return PopupMenuItem(
              value: e.key,
              child: Text("${e.value['description']}"));
        }).toList(),
        onSelected: (newvalue){
          controller.updateLocale(newvalue);
        },
      ),
    );
  }

}
Dart