skip to Main Content

I use getxcontroller, in it there is a String like this:

class HomeController extends GetxController {
  String testString1 = 'test1'.tr;

  testMethod(){
   String testString2 = 'test2'.tr;
 }
}

After I trigger some localise method:

var locale = Locale('de', 'DE');
Get.updateLocale(locale);

testString2 is fine to be translated into German, but testString1 not works, since I will update value of testString1 in other method, and testString1 should have initial value.

I tried RxString/.obs, but not works, what is the right way to fix this issue?

2

Answers


  1. When you write

    String testString1 = 'test1'.tr;
    

    testString1 gets set the moment the controller is created and will never change after, even if you update the locale. What you could do is turn it into a getter so it gets the latest translation everytime it’s accessed like

    String get testString1 => 'test1'.tr;
    
    Login or Signup to reply.
  2. /// this is the map for the key pair value
    Map<String, Map<String, String>> get keys => {
        'en_US': {
          "hello": "Hello enter code here",
        },
        'hi_IN': {
          "hello": "नमस्ते",
        },
        'fr_FR': {
          'hello': 'bonjour',
        }
      };
    
     /// this is the method for translate the string
       void changeLanguage(String param1, String param2) {
          var local = Locale(param1, param2);
          Get.updateLocale(local);
       }
    
     /// This is Ui 
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: [
            Text(
           "hello".tr,
           style: const TextStyle(
             fontSize: 24,
           ),
         ),
         ElevatedButton(
            onPressed: () {
              Get.find<MyController>().changeLanguage('en', 'US');
            },
               child: const Text("English"),
            ),
            ElevatedButton(
               onPressed: () {
                  Get.find<MyController>().changeLanguage("hi", "IN");
               },
                  child: const Text("Hindi"),
               ),
               ElevatedButton(
                  onPressed: () {
                     Get.find<MyController>().changeLanguage("fr", "FR");
                  },
                  child: const Text("French"),
               ),
            ],
         ),
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search