Localization , How to change language in Flutter 3 using Getx

Localization , How to change language in Flutter 3 using Getx

14-Sep-2024
| |
Image Carousel

Hello developers in this tutorial we will discuss about how to change language of all screens in flutter by using Getx package

Table of Contents

S.no Contents-topics
1 Import packages  
2 Configure main.dart
3 Creating messages translation file
4 Controller for toggle languages
5 Run the code

1:Import packages

In pubspec.yaml we need to import some packages (version of packages may differ so import latest pacakges from Pub Dev)
get:^4.6.5 - For using Getx packages (obx,updateLocale(),GetxController) 
shared_preferences: ^2.0.15 - For saving data into local storage of device
localize_and_translate: ^4.1.1 - For translating all strings into the app

Dependecies code Copy

 get: ^4.6.5
  shared_preferences: ^2.0.15
  localize_and_translate: ^4.1.1 

2:Configure main.dart

In main.dart we import or all packages and define our controller and translation 
main.dart code 
Copy

import 'package:flutter/material.dart';
import 'package:get/get.dart';
 
import 'localization/change_language_controller.dart';
import 'localization/messages.dart';
 
void main() {
  runApp(MyApp());
}
 
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      translations: Messages(),
      home: HomePage(),
    );
  }
}
 
class HomePage extends StatelessWidget {
  @override
  var controller = Get.put(ChangeLanguageController());
  Widget build(BuildContext context) {
    double screenWidth = MediaQuery.of(context).size.width;
    double screenheight = MediaQuery.of(context).size.height;
    return Scaffold(
        appBar: AppBar(
          title: Text('Localization with Getx'),
        ),
        body: Container(
          color: Colors.purple[300],
          child: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text('welcome_msg'.tr,
                    style: const TextStyle(fontSize: 20, color: Colors.white)),
                SizedBox(
                  height: 50,
                ),
                Text('local'.tr,
                    style: const TextStyle(fontSize: 20, color: Colors.white)),
                SizedBox(
                  height: 50,
                ),
                Text('thankyou'.tr,
                    style: const TextStyle(fontSize: 20, color: Colors.white)),
                SizedBox(
                  height: 50,
                ),
                Obx(() => SizedBox(
                    height: 50,
                    width: screenWidth - 10,
                    child: ElevatedButton(
                        style: ElevatedButton.styleFrom(
                          backgroundColor: Colors.purple,
                        ),
                        onPressed: () {
                          if (controller.language.value == "en") {
                            controller.SaveStringToSF("en", "US");
                            controller.changeLanguage("en", "US");
                            controller.language.value = 'hi';
                          } else {
                            controller.SaveStringToSF("hi", "IN");
                            controller.changeLanguage("hi", "IN");
                            controller.language.value = 'en';
                          }
                        },
                        child: controller.language.value == 'hi'
                            ? Text(
                                'Click to change'.tr,
                                style: const TextStyle(
                                  fontSize: 20,
                                ),
                              )
                            : Text(
                                'Click to change'.tr,
                                style: const TextStyle(
                                  fontSize: 20,
                                ),
                              ))))
              ],
            ),
          ),
        ));
  }
}

3:Creating messages translation file

Under the lib folder create a folder name localization and inside localization create two files messages.dart , change_language_controller.dart , in message.dart we difine our all strings we want to toggle or show in different language as shown we are using "en_US" , "hi_IN" "en_US"-> English , "hi_IN"->Hindi
code for message.dart: Copy

import 'package:get/get.dart';
 
class Messages extends Translations {
  @override
  // TODO: implement keys
  Map<String, Map<String, String>> get keys => {
        'en_US': {
          "welcome_msg": "Welcome to DeveloperCodez.com",
          "local": "This is feature post for localization in flutter",
          "thankyou": "Thankyou for watching this post",
          "change": "Click to change"
        },
        'hi_IN': {
          "welcome_msg": "DeveloperCodez.com में आपका स्वागत है",
          "local": "यह Flutter में स्थानीयकरण के लिए फीचर पोस्ट है",
          "thankyou": "इस पोस्ट को देखने के लिए धन्यवाद",
          "change": "बदलने के लिए क्लिक करें"
        },
      };
}

Also read:DECORATE TEXTFIELD IN FLUTTER 3 , INPUTTEXTFIELD DECORATION IN FLUTTER 3

4: Controller for toggle languages

In lib/localization/change_language_controller.dart we define our function 
checkLocaleLanguage() => For checking if user has already setup language before from shared prefrences
changeLanguage() => To change the language of App and also save in local storage
code for Controllerr
Copy

import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter/material.dart';
 
class ChangeLanguageController extends GetxController {
  var language = ''.obs;
 
  @override
  void onInit() {
    // language Prefernce
    // CheckUserConnection();
 
    checkLocaleLanguage();
    super.onInit();
  }
 
  void checkLocaleLanguage() async {
    var pref = await SharedPreferences.getInstance();
    language.value = pref.getString('language').toString();
    if (language.value != '') {
      if (language.value == 'hi') {
        changeLanguage('hi', 'IN');
      } else {
        changeLanguage('en', 'US');
      }
    } else {
      changeLanguage('en', 'US');
    }
    // check Connection
  }
 
  void changeLanguage(var languageCode, var CountryCode) async {
    // print('language--$CountryCode');
    print('language--$language');
    var locale = Locale(languageCode, CountryCode);
    await Get.updateLocale(locale);
  }
 
  SaveStringToSF(var key, var value) async {
    var pref = await SharedPreferences.getInstance();
    pref.setString(key, value).toString();
    return true;
  }
}

5: Run the Code

 

Tags: localization , how to change language in flutter using getx package , how to change language of all screens using getx in flutter , localization by using getx in flutter,flutter, mobile app development, dart, UI, widgets, framework, cross-platform, iOS, Android, web, desktop, Fuchsia, Material Design, Cupertino, animation, state management, reactive programming, asynchronous programming.,
0 Comments (Please let us know your query)
Leave Comment
Leave Comment
Articles from other Categories
Load More

Newsletter