getx icon indicating copy to clipboard operation
getx copied to clipboard

After Get.updateLocale is called, how can the current page Controller be reinitialized?

Open Aaron009 opened this issue 2 years ago • 1 comments

Get.updateLocale(Locale('pt', 'BR'))

Because I have such a scenario now, after calling this function, I need to re-request information from the network, so that the correct text interface can be displayed correctly.

Aaron009 avatar Aug 02 '22 16:08 Aaron009

如果你用obx方式的话,你可以尝试一下。

  1. 在Controller内,创建值 final RxString currentLocale = 'en_US'.obs;

  2. 更改语言的函数

void changeLocale() {
 if (currentLocale.value == 'en_US') {
   Get.updateLocale(Locale('zh', 'CN'));
   currentLocale.value == 'zh_CN';
  } else {
   Get.updateLocale(Locale('en', 'US'));
   currentLocale.value == 'en_US';
}
  1. 创建接口
Future<String> getData(String locale) async {
  await Future<void>.delayed(const Duration(seconds: 2));
  if (param == 'en_US') {
    return 'Hello World';
  } else {
    return '你好世界';
  }
}
  1. 在UI内,使用FutureBuilder部件
Obx(
  () => FutureBuilder<String>(
    future: mouController.getData(mouController.locale.value),
    builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
      if (snapshot.connectionState == ConnectionState.done) {
        return Text(snapshot.data!);
      } else {
        return const Text('Loading...');
      }
    },
  ),
),

如有问题,回复里贴下你的代码哈。

iamshaunwu avatar Aug 03 '22 04:08 iamshaunwu