likes
comments
collection
share

Flutter 日记APP-get国际化

作者站长头像
站长
· 阅读数 5

get 配置

根据get的使用文档,使用get先在main.dart中使用GetMaterialApp替换Flutter自带的MaterialApp。

Widget build(BuildContext context) {
  return GetMaterialApp(
  //全局导航key,用于获取当前的context
    navigatorKey: SSLUIManager.sslNavKey,
    //是否显示右上角debug图片
    debugShowCheckedModeBanner: false,
    //国际化翻译管理类,下面介绍
    translations: SSLInternation(),
    //当前的主题,下文介绍
    theme: sslUI.currentTheme,
    // darkTheme: SSLColor.darkTheme,
    //get路由管理,后续介绍
    getPages: SSLRoutes.pages,
    //初始路由
    initialRoute: SSLRoutes.root_routes,
    //主页,和初始路由相同
    home: const SSLRootRoute(),
    //当前语言
    locale: sslUI.currentLocale,
    //本地语言发生变化后回调
    localeListResolutionCallback: (locales, supportedLocales){
      debugPrint("当前系统语言环境$locales");
      return;
    },
    //当前语言不支持的语言类型时使用的默认语言
    fallbackLocale: const Locale('en', 'US'),
  );
}

文件类容

配置好对应的设置后,来看下get的国际化管理文件类SSLInternation,内容很简单。

import 'package:get/get.dart';
import 'locales/intl_en_us.dart';//英文
import 'locales/intl_zh_cn.dart';/中文
class SSLInternation extends Translations{
  @override
  Map<String, Map<String, String>> get keys {
    return {
        'zh_cn' : intlZhCN,//对应的中文翻译
        'en_us' : intlEnUS,//对应英文翻译
    };
  }
}

对应的中文

import 'package:file_handle/internation/SSLIntlName.dart';
final Map<String, String> intlEnUS = {
  SSLLocales.main_tab_home : "Lift",
  SSLLocales.main_tab_charts : "Charts",
  SSLLocales.main_tab_setting : "Setting",
  ...
}

其中SSLLocales.main_tab_home,是定义的常量,便于使用时不用直接硬敲字符串,容易出错。也顺便贴出源码。

abstract class SSLLocales {
  //命名规则一级名_二级名_具体名,不可超过两级
  static const main_tab_home = "main_tab_home";
  static const main_tab_charts = "main_tab_charts";
  static const main_tab_setting = "main_tab_setting";
  ...
}

使用

//加上tr后缀则会被get监听,当切换语言时,会更新到对应的语言。
Text(SSLLocales.main_tab_home.tr),

切换语言

Future<bool> changeLocal(String local) async{
    if (local == sslLocale){
      return false;
    }
    //本地存储
    bool success = await shareSetStringData(localeKey, local);
    if (success){
    //设置当前语言标识
      localeSet = local;
      //获取当前语言的Locale
      Locale temLocal = currentLocale;
      //使用get更新语言,会更新全局,待tr的String显示
      Get.updateLocale(temLocal);
    }
    return success;
}

总体来讲,使用get进行国际化管理还是很方便的,可能在部分功能上没有intl 灵活方便,但对于大多项目来说,完全够用了,特别是和get 功能配合使用,会更加的酸爽。