Flutter:如何在GetxController中更新locale

ibps3vxo  于 2023-06-07  发布在  Flutter
关注(0)|答案(1)|浏览(220)

我的splash代码

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(),
    );
  }
}

更新控制器中的区域设置后

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!;
  }
}

此代码未更新

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

如何修复?它在LocaleController控制器中更新,但在app类中,它始终返回fa_FA,并且不显示更新的区域设置。

wr98u20j

wr98u20j1#

如文档所述,您需要调用;
getx

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

您需要使用预期的Locale调用此方法。
此外,可以使用检查当前区域设置;

Get.locale;

相关问题