You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中使用GetX实现页面自动适配语言及切换语言后跳转生效方案

完整实现步骤

1. 引入依赖

首先在pubspec.yaml中添加必要依赖:

dependencies:
  flutter:
    sdk: flutter
  get: ^4.6.5
  get_storage: ^2.1.1

2. 实现多语言翻译配置

新建翻译配置类,继承GetX的Translations类,定义各语言对应的键值对:

class AppTranslations extends Translations {
  @override
  Map<String, Map<String, String>> get keys => {
    'en_US': {
      'serverAddress': 'Server Address',
      // 补充其他所有需要国际化的key
    },
    'zh_CN': {
      'serverAddress': '服务器地址',
      // 补充其他所有需要国际化的key
    }
    // 可继续添加其他语言配置
  };
}

3. 初始化全局配置

在main函数中完成存储、GetX全局配置,启动时自动读取本地存储的语言设置,没有存储则默认适配系统语言:

void main() async {
  // 初始化本地存储
  await GetStorage.init();
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    // 读取本地存储的语言,不存在则用系统语言
    final box = GetStorage();
    String? storedLang = box.read('lang');
    Locale initLocale;
    if (storedLang != null) {
      List<String> langParts = storedLang.split('_');
      initLocale = Locale(langParts[0], langParts[1]);
    } else {
      // 适配系统语言,可根据需求添加兜底逻辑
      initLocale = Get.deviceLocale ?? const Locale('en', 'US');
    }

    return GetMaterialApp(
      // 配置翻译规则
      translations: AppTranslations(),
      // 初始语言
      locale: initLocale,
      // 找不到对应语言时的兜底语言
      fallbackLocale: const Locale('en', 'US'),
      home: const LanguageSelectPage(), // 替换为你的实际启动页
    );
  }
}

4. 优化语言选择页逻辑

你现有代码缺少调用GetX更新全局语言的方法,切换语言时除了存本地,还要调用Get.updateLocale触发全局语言刷新:

// 选择英文的点击逻辑优化
onPressed: () {
  final box = GetStorage();
  box.write('lang', 'en_US');
  // 关键:调用此方法触发全局语言实时更新
  Get.updateLocale(const Locale('en', 'US'));
  Get.to(() => LoginScreen1());
},
// 选择中文逻辑参考:
// onPressed: () {
//   final box = GetStorage();
//   box.write('lang', 'zh_CN');
//   Get.updateLocale(const Locale('zh', 'CN'));
//   Get.to(() => LoginScreen1());
// },

5. 页面中使用国际化

所有需要多语言的文本直接用.tr后缀调用即可,和你现有写法一致:

Text('serverAddress'.tr)

切换语言后所有已加载、后续加载的页面都会自动适配新语言,不需要额外处理。

内容的提问来源于stack exchange,提问作者user16867349

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 02:06:03