关于Flutter应用国际化语言的设置

目录

[1. Locale配置](#1. Locale配置)

[2. 用户切换/启动自动加载缓存里面的locale](#2. 用户切换/启动自动加载缓存里面的locale)


由于最近在开发app国际化设置的时候遇到一些问题,所以做出一些总结。

1. Locale配置

具体的初始化配置可以参考文档:i18n | Flutter 中文文档 - Flutter 中文开发者网站 - Flutter

值得注意的是这里记得要加上自己的delegate,不然启动会有context相关的问题。(dependOnInheritedWidgetOfExactType<_LocalizationsScope>() or dependOnInheritedElement() was called before _HomeViewState.initState() completed.)

作为一些补充也可以参考:Flutter实现国际化(多语言)_flutter 国际化-CSDN博客

2. 用户切换/启动自动加载缓存里面的locale

Dart 复制代码
void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  // Load the cached locale before the app starts
  Storage().getData(CommonSpKey.locale.value).then((cachedLanguageCode) {
    runApp(ChangeNotifierProvider(
      create: (_) {
        final provider = LocaleProvider();
        provider.init(Locale(cachedLanguageCode ?? 'zh'));
        return provider;
      },
      child: MyApp(cachedLocale: Locale(cachedLanguageCode ?? 'zh')),
    ),);
  });
}
Dart 复制代码
Future<String?> getData(String key) async {
    final preference = await SharedPreferences.getInstance();
    return preference.getString(key);
  }

简单来说,这里是在main.dart里面启动的时候加载缓存的语言,然后通过MyApp这个widget的localeResolutionCallback来设置当前显示的locale。

updatedLocale是用户当前选择的所以优先显示,

如果没有就读取cacheLocale的,

如果还是没有就读取系统环境的locale。

Dart 复制代码
final Locale? updatedLocale = context.watch<LocaleProvider>().currentLocale;

--

localeResolutionCallback: (locale, supportedLocales) {
  if (updatedLocale != null) {
    // print('---------> 1: ${updatedLocale.languageCode}');
    return Locale(updatedLocale.languageCode);
  }
  if(cachedLocale != null) {
    // print('---------> 2: ${cachedLocale!.languageCode}');
    return cachedLocale;
  }
  // print('---------> 3');
  if (locale?.countryCode == 'US') {
    return const Locale('en', 'US');
  } else {
    return const Locale('zh', 'CN');
  }
},
locale: cachedLocale, // Default locale
相关推荐
张风捷特烈21 小时前
Flutter 伪3D绘制#03 | 轴测投影原理分析
android·flutter·canvas
马拉萨的春天1 天前
flutter 项目结构目录以及pubspec.ymal等文件描述
flutter
bst@微胖子2 天前
Flutter项目之登录注册功能实现
开发语言·javascript·flutter
小墙程序员2 天前
Flutter 教程(十一)多语言支持
flutter
无知的前端2 天前
Flutter 一文精通Isolate,使用场景以及示例
android·flutter·性能优化
yidahis2 天前
Flutter 运行新建项目也报错?
flutter·trae
木马不在转2 天前
Flutter-权限permission_handler插件配置
flutter
江上清风山间明月2 天前
一周掌握Flutter开发--9. 与原生交互(下)
flutter·交互·原生·methodchannel
GeniuswongAir2 天前
Flutter极速接入IM聊天功能并支持鸿蒙
flutter·华为·harmonyos
sayen2 天前
记录 flutter 文本内容展示过长优化
前端·flutter