Search code examples
flutterflutter-getx

Flutter: How to update locale in GetxController


my splash code this

class App extends StatelessWidget {
  const App();

  @override
  Widget build(BuildContext context) {
    Get.put(SplashController());
    Get.put(ThemeController());
    Get.put(HomeController());
    Get.put(LocaleController());
    var localeController = Get.find<LocaleController>();
    print('amirrrrrrrrrrr${localeController.locale}');
    return GetMaterialApp(
      debugShowCheckedModeBanner: false,
      translations: LocaleString(),
      locale: localeController.locale,
      initialBinding: MyBindings(),
      home: Splash(),
    );
  }
}

after update locale in controller

class LocaleController extends GetxController {
  Locale locale = const Locale('fa', 'FA');

  Future<void> saveLocale(Locale newLocale) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setString('languageCode', newLocale.languageCode);
    await prefs.setString('countryCode', newLocale.countryCode.toString());
    locale = newLocale;
    update();
    print('amirrrrrrr$locale');
  }

  Future<Locale> loadLocale() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String? languageCode = prefs.getString('languageCode');
    String? countryCode = prefs.getString('countryCode');
    Locale? locale;
    if (languageCode != null && countryCode != null) {
      locale = Locale(languageCode, countryCode);
      this.locale = locale;
    }
    update();
    print('amirrrrrrr$locale');
    return locale!;
  }
}

this code not updated

var localeController = Get.find<LocaleController>();
print('amirrrrrrrrrrr${localeController.locale}');

how to fix ? It is updated in the LocaleController controller, but in the app class, it always returns fa_FA and does not show the updated locale.


Solution

  • As documentation mentioned you need to call;

    getx

    Get.changeLocale(Locale("pt"));
    

    You need to call this method with expected Locale.

    Additionally, current locale can be checked with;

      Get.locale;