Flutter国际化语言轻松搞定

Flutter国际化

1.引入依赖

yaml 复制代码
dependencies: 
 intl: ^0.20.2
  flutter_localizations:
    sdk: flutter
 
 flutter:
  # 针对多语言 l10n
  generate: true

2.在项目根目录创建 l10n.yaml 配置文件

yaml 复制代码
arb-dir: lib/common/config/localization/l10n # 多语言资源文件的目录
template-arb-file: app_en.arb 	 # 基础模板文件(通常为英文)
output-localization-file: app_localizations.dart # 生成的国际化代码文件名
output-class: AppLocalizations # 生成的国际化类名
preferred-supported-locales:
  - en
  - zh
synthetic-package: false

3.创建语言文件 app_en.arb, app_zh.arb

txt 复制代码
zh:
{
  "welcomeMessage": "Welcome To Flutter",
  "app_name": "WarmTodo",
  "today": "今天",
  "no_todo": "暂无待办事项",
  "todo": "待办事项",
  "enter_todo": "输入待办事项...",
  "save": "保存",
  "mark_completed": "标记为完成",
  "mark_uncompleted": "标记为未完成",
  "priority": "优先级",
  "low": "低优先级",
  "medium": "中优先级",
  "high": "高优先级"
}

en:

{
  "welcomeMessage": "Welcome To Flutter",
  "app_name": "WarmTodo",
  "today": "Today",
  "no_todo": "There are no pending tasks",
  "todo": "To-do",
  "enter_todo": "Enter the to-do items",
  "save": "Save",
  "mark_completed": "Marked as finished",
  "mark_uncompleted": "Marked as unfinished",
  "priority": "Priority",
  "low": "Low priority",
  "medium": "Medium priority",
  "high": "High priority"
}

4.执行 flutter gen-l10n 命令

保存配置后,执行 flutter gen-l10n 命令,Flutter 会自动在 lib/generated 目录下生成 app_localizations.dart 文件,该文件包含所有多语言文案的访问方法。

5.在应用中配置本地化代理

dart 复制代码
void main() {
  runApp(const MyApp());
}

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

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      localizationsDelegates: AppLocalizations.localizationsDelegates, //配置本地化代理(必须)
      //配置应用支持的语言列表
      supportedLocales: [
        const Locale('en','US'),
        const Locale('zh','CN'),
      ],
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: .fromSeed(seedColor: Colors.deepPurple),
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

6.通过扩展方法(Extension)封装国际化工具类的便捷调用

dart 复制代码
import 'package:flutter/material.dart';
import 'l10n/app_localizations.dart';

extension LocalizationExtension on BuildContext {
  AppLocalizations get l10n => AppLocalizations.of(this)!;
}

7.在组件中使用

dart 复制代码
Text(context.l10n.app_name)

恭喜!你学会了Flutter国际化!Happy Coding !😊😊😊

相关推荐
神经蛙39716 小时前
settings.gradle' line: 22 * What went wrong: Plugin [id: 'org.jetbrains.kotlin.a
flutter
stringwu7 小时前
一个bug 引发的Dart 与 Java WeakReference 对比探讨
flutter
火柴就是我1 天前
从头写一个自己的app
android·前端·flutter
●VON1 天前
Flutter 项目成功运行后,如何正确迁移到 OpenHarmony?常见疑问与跳转失效问题解析
flutter·华为·openharmony·开源鸿蒙
●VON1 天前
Flutter 编译开发 OpenHarmony 全流程实战教程(基于 GitCode 社区项目)
flutter·openharmony·gitcode
消失的旧时光-19432 天前
Flutter 组件:Row / Column
flutter
程序员老刘2 天前
Flutter版本选择指南:3.35稳定,3.38发布 | 2025年11月
flutter·客户端
kirk_wang2 天前
Flutter 3.38和Dart 3.10中最大的更新
flutter
前端小伙计2 天前
Flutter 配置国内镜像,加速项目加载!
flutter