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 !😊😊😊

相关推荐
leazer13 小时前
Flutter Windows 构建失败:.plugin_symlinks 符号链接异常的排查与修复
windows·flutter
小蜜蜂嗡嗡1 天前
flutter image_cropper截图控件布局顶到状态栏中问题
flutter
程序员老刘1 天前
跨平台开发地图:大厂统一底层,五月框架大乱斗谁在干实事?| 2026年5月
flutter·客户端
环信即时通讯云2 天前
环信Flutter UIKit适配鸿蒙实战指南
flutter·华为·harmonyos
用户536822100182 天前
flutter学习笔记 - Dart基本语法(一)
flutter
用户游民2 天前
Flutter Provider原理以及用法
前端·flutter
qq_14030341442 天前
flutter
flutter
程序员老刘2 天前
为什么AI不会淘汰Flutter,反而让它更吃香了
flutter·ai编程·客户端
蝎子莱莱爱打怪2 天前
我花两年业余时间做了个IM系统,然后呢😂??
后端·flutter·面试