关于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
相关推荐
season_zhu2 小时前
聊聊我最近都干了些什么,AI 时代的手动撸码人
flutter·ios·ai编程
2501_915106323 小时前
Flutter 开发工具有哪些 跨平台项目开发与上架实操指南
android·flutter·ios·小程序·uni-app·iphone·webview
吃不胖爹3 小时前
flutter项目如何打包,创建签名与配置签名
javascript·flutter·架构
weixin_443478514 小时前
Flutter学习之输入组件
学习·flutter·servlet
吃不胖爹4 小时前
Flutter 基本架构与使用
javascript·flutter·架构
MakeZero18 小时前
Flutter那些事-GridView
flutter·dart
Gorit1 天前
使用 AI + Flutter-OH 开发 HarmonyOS 应用
人工智能·flutter·harmonyos
啥都想学点1 天前
从 Flutter 前端到 Spring Boot 后端:2026 年技术栈落地路线图(实战版)
前端·spring boot·flutter
西西学代码2 天前
Flutter---回调函数
开发语言·javascript·flutter