有没有Flutter国际化支持教程推荐?

我正在学习Flutter的国际化支持,但在实现过程中遇到些问题,比如如何正确配置arb文件?多个语言的文件命名和路径有什么规范?

有没有Flutter国际化支持教程推荐?

2 回复

Flutter支持多语言非常方便,使用flutter_localizations插件即可。首先定义不同语言的资源文件,比如locale_en.arblocale_zh.arb,内容类似:{“hello”:“Hello”,“welcome”:“Welcome”}。然后配置pubspec.yaml:dependencies下加入flutter_localizationsintl,并在flutter字段指定gen-l10n脚本路径。接着创建Locale类管理语言,通过MaterialApp的localizationsDelegates与supportedLocales设置多语言支持。切换语言时,调用setState()刷新UI。最后在代码中用AppLocalizations.of(context)!.key获取对应文字。简单几步就能实现国际化,非常适合开发多语言应用。

更多关于有没有Flutter国际化支持教程推荐?的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


Flutter国际化支持教程

Flutter提供了强大的国际化(i18n)支持,以下是实现国际化的基本步骤:

1. 添加依赖

pubspec.yaml中添加:

dependencies:
  flutter_localizations:
    sdk: flutter
  intl: ^0.17.0

2. 创建国际化文件

创建lib/l10n目录,然后添加app_localizations.dart

import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:intl/intl.dart';
import 'l10n/messages_all.dart';

class AppLocalizations {
  static Future<AppLocalizations> load(Locale locale) {
    final String name = locale.countryCode.isEmpty ? locale.languageCode : locale.toString();
    final String localeName = Intl.canonicalizedLocale(name);
    return initializeMessages(localeName).then((_) {
      Intl.defaultLocale = localeName;
      return AppLocalizations();
    });
  }

  static AppLocalizations of(BuildContext context) {
    return Localizations.of<AppLocalizations>(context, AppLocalizations)!;
  }

  String get helloWorld => Intl.message('Hello World', name: 'helloWorld');
}

3. 创建ARB文件

创建lib/l10n/app_en.arb

{
  "@@locale": "en",
  "helloWorld": "Hello World",
  "@helloWorld": {
    "description": "The conventional newborn programmer greeting"
  }
}

创建lib/l10n/app_es.arb(西班牙语示例):

{
  "@@locale": "es",
  "helloWorld": "Hola Mundo"
}

4. 生成代码

在终端运行:

flutter pub run intl_translation:generate_from_arb --output-dir=lib/l10n --no-use-deferred-loading lib/l10n/app_localizations.dart lib/l10n/app_*.arb

5. 设置MaterialApp

return MaterialApp(
  localizationsDelegates: [
    AppLocalizations.delegate,
    GlobalMaterialLocalizations.delegate,
    GlobalWidgetsLocalizations.delegate,
  ],
  supportedLocales: [
    const Locale('en'), // English
    const Locale('es'), // Spanish
  ],
  home: MyHomePage(),
);

6. 使用国际化文本

Text(AppLocalizations.of(context)!.helloWorld)

高级功能

  • 可以添加更多语言支持
  • 支持复数形式和性别相关文本
  • 可以通过Intl实现日期/数字本地化

这就是Flutter国际化的基本实现方式。需要定期运行代码生成命令来更新翻译文件。

回到顶部