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

如何在GetX框架中实现hintText提示文本的多语言翻译

GetX 框架下翻译 hintText 实现方法

1. 编写多语言翻译映射类

继承GetX提供的Translations类,配置不同语言对应的键值对:

import 'package:get/get.dart';

class AppTranslations extends Translations {
  @override
  Map<String, Map<String, String>> get keys => {
    // 简体中文翻译配置
    'zh_CN': {
      'country_code': '国家/地区代码',
      // 其余需要翻译的文本都可以按照键值对格式在这里添加
    },
    // 英文翻译配置
    'en_US': {
      'country_code': 'Country Code',
    }
  };
}

2. 初始化Get应用时注册翻译配置

修改GetMaterialApp的初始化参数,注入翻译配置、默认语言和兜底语言:

void main() {
  runApp(const MyApp());
}

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

  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      // 注册自定义的翻译类
      translations: AppTranslations(),
      // 设置默认显示语言为简体中文
      locale: const Locale('zh', 'CN'),
      // 当当前语言没有对应翻译时,兜底显示英文
      fallbackLocale: const Locale('en', 'US'),
      home: const YourHomePage(),
    );
  }
}

3. 修改业务代码的hintText属性

给需要翻译的字符串添加GetX提供的.tr扩展方法即可:

InternationalPhoneNumberInput(
    searchBoxDecoration: InputDecoration(
        hintText: 'country_code'.tr,
    ),
)

注意事项

  • 翻译映射类中的key必须和业务代码中调用.tr的字符串完全一致,大小写敏感,否则会直接显示原字符串
  • 如需切换应用语言,调用Get.updateLocale(const Locale('en', 'US'))即可全局生效,无需手动刷新页面

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 13:36:04