1. 插件介绍

Flutter Localization 是一个用于应用内本地化的 Flutter 包,它使用 Map 数据结构存储多语言资源,使本地化实现更加简单高效。该包已针对鸿蒙平台进行适配,确保在鸿蒙设备上稳定运行。

核心功能

  • 基于 Map 的本地化:使用键值对形式存储多语言资源,易于管理和维护
  • 动态语言切换:支持在应用运行时无缝切换语言,无需重启应用
  • 字符串翻译:提供简洁的 API 实现字符串翻译功能
  • 字体族支持:可针对不同语言配置特定字体
  • 格式化字符串:支持动态参数替换的字符串格式化功能

适用场景

  • 需要支持多语言的 Flutter 应用
  • 需要动态切换语言的场景
  • 希望使用简洁 API 实现本地化的项目
  • 在鸿蒙平台上开发的 Flutter 应用

2. 安装与配置

2.1 依赖配置

由于这是一个针对鸿蒙平台的自定义修改版本,需要通过 Git 形式引入。在项目的 pubspec.yaml 文件中添加以下依赖配置:

dependencies:
  flutter_localization:
    git:
      url: "https://atomgit.com/openharmony-sig/flutter_localization.git"

2.2 安装依赖

执行以下命令安装依赖:

flutter pub get

3. 使用方法

3.1 准备语言资源

创建一个 Dart 文件用于存放多语言资源,使用 Map 结构定义不同语言的字符串:

mixin AppLocale {
  static const String title = 'title';
  static const String welcomeMessage = 'welcomeMessage';
  static const String changeLanguage = 'changeLanguage';

  static const Map<String, dynamic> EN = {
    title: 'Flutter Localization',
    welcomeMessage: 'Welcome to Flutter Localization package!',
    changeLanguage: 'Change Language'
  };

  static const Map<String, dynamic> ZH = {
    title: 'Flutter 本地化',
    welcomeMessage: '欢迎使用 Flutter Localization 包!',
    changeLanguage: '切换语言'
  };

  static const Map<String, dynamic> JA = {
    title: 'Flutter ローカリゼーション',
    welcomeMessage: 'Flutter Localization パッケージへようこそ!',
    changeLanguage: '言語を変更する'
  };
}

3.2 初始化配置

在应用入口处初始化 FlutterLocalization 实例:

import 'package:flutter/material.dart';
import 'package:flutter_localization/flutter_localization.dart';
import 'app_locale.dart';

void main() {
  runApp(const MyApp());
}

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

  
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final FlutterLocalization _localization = FlutterLocalization.instance;

  
  void initState() {
    _localization.init(
      mapLocales: [
        const MapLocale('en', AppLocale.EN),
        const MapLocale('zh', AppLocale.ZH),
        const MapLocale('ja', AppLocale.JA),
      ],
      initLanguageCode: 'en',
    );
    _localization.onTranslatedLanguage = _onTranslatedLanguage;
    super.initState();
  }

  void _onTranslatedLanguage(Locale? locale) {
    setState(() {});
  }

  
  Widget build(BuildContext context) {
    return MaterialApp(
      supportedLocales: _localization.supportedLocales,
      localizationsDelegates: _localization.localizationsDelegates,
      home: const HomeScreen(),
    );
  }
}

3.3 翻译字符串

在 Widget 中使用 getString() 扩展方法获取本地化字符串:

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

  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(AppLocale.title.getString(context)),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              AppLocale.welcomeMessage.getString(context),
              style: const TextStyle(fontSize: 18),
              textAlign: TextAlign.center,
            ),
            const SizedBox(height: 20),
            Text(
              AppLocale.changeLanguage.getString(context),
              style: const TextStyle(fontSize: 16),
            ),
          ],
        ),
      ),
    );
  }
}

3.4 切换语言

使用 translate() 方法切换应用语言:

class HomeScreen extends StatefulWidget {
  const HomeScreen({super.key});

  
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  final FlutterLocalization _localization = FlutterLocalization.instance;

  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(AppLocale.title.getString(context)),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              AppLocale.welcomeMessage.getString(context),
              style: const TextStyle(fontSize: 18),
              textAlign: TextAlign.center,
            ),
            const SizedBox(height: 40),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                ElevatedButton(
                  child: const Text('English'),
                  onPressed: () {
                    _localization.translate('en');
                  },
                ),
                const SizedBox(width: 10),
                ElevatedButton(
                  child: const Text('中文'),
                  onPressed: () {
                    _localization.translate('zh');
                  },
                ),
                const SizedBox(width: 10),
                ElevatedButton(
                  child: const Text('日本語'),
                  onPressed: () {
                    _localization.translate('ja');
                  },
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

3.5 高级功能

3.5.1 配置字体族

可以为不同语言配置特定字体:

_localization.init(
  mapLocales: [
    const MapLocale('en', AppLocale.EN, fontFamily: 'Roboto'),
    const MapLocale('zh', AppLocale.ZH, fontFamily: 'NotoSansSC'),
    const MapLocale('ja', AppLocale.JA, fontFamily: 'NotoSansJP'),
  ],
  initLanguageCode: 'en',
);

然后在 MaterialApp 中使用:

MaterialApp(
  // ...
  theme: ThemeData(fontFamily: _localization.fontFamily),
  // ...
)
3.5.2 格式化字符串

使用 formatString() 方法实现带参数的字符串格式化:

// 在 AppLocale 中定义
static const String greeting = 'greeting';

static const Map<String, dynamic> EN = {
  // ...
  greeting: 'Hello, %a! Welcome to %a.',
  // ...
};

// 使用
Text(context.formatString(AppLocale.greeting, ['John', 'Flutter'])),
// 输出: Hello, John! Welcome to Flutter.

4. API 参考

4.1 FlutterLocalization 核心 API

方法名 描述 参数 返回值 鸿蒙支持
init() 初始化本地化配置 mapLocales:语言资源列表
initLanguageCode:初始语言代码
Future<void>
translate() 切换语言 languageCode:目标语言代码
save:是否保存语言设置(默认:true)
void
getLanguageName() 获取语言名称 languageCode:语言代码(可选,默认当前语言) String

4.2 扩展方法

方法名 描述 参数 返回值
getString() 获取本地化字符串 context:BuildContext String
formatString() 格式化字符串 text:原始字符串
args:参数列表
String

4.3 核心属性

属性名 描述 类型
supportedLocales 支持的语言列表 Iterable<Locale>
localizationsDelegates 本地化代理 Iterable<LocalizationsDelegate<dynamic>>
currentLocale 当前语言 Locale?
fontFamily 当前语言的字体族 String?

5. 约束与限制

  • Flutter 版本:支持 Flutter 3.7.12-ohos-1.1.3+ 和 3.22.1-ohos-1.0.3+
  • 鸿蒙 SDK:支持鸿蒙 SDK 5.0.0+
  • IDE:推荐使用 DevEco Studio 5.1.0.828+

6. 示例代码

以下是一个完整的鸿蒙平台 Flutter Localization 使用示例:

import 'package:flutter/material.dart';
import 'package:flutter_localization/flutter_localization.dart';

mixin AppLocale {
  static const String title = 'title';
  static const String welcome = 'welcome';
  static const String switchLanguage = 'switchLanguage';
  static const String currentLanguage = 'currentLanguage';
  static const String helloFormat = 'helloFormat';

  static const Map<String, dynamic> EN = {
    title: 'Localization Demo',
    welcome: 'Welcome to Flutter Localization on HarmonyOS',
    switchLanguage: 'Switch Language',
    currentLanguage: 'Current Language',
    helloFormat: 'Hello %a! This is %a.',
  };

  static const Map<String, dynamic> ZH = {
    title: '本地化示例',
    welcome: '欢迎在鸿蒙平台上使用 Flutter Localization',
    switchLanguage: '切换语言',
    currentLanguage: '当前语言',
    helloFormat: '你好,%a!这是%a。',
  };
}

void main() {
  runApp(const MyApp());
}

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

  
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final FlutterLocalization _localization = FlutterLocalization.instance;

  
  void initState() {
    _localization.init(
      mapLocales: [
        const MapLocale('en', AppLocale.EN),
        const MapLocale('zh', AppLocale.ZH),
      ],
      initLanguageCode: 'en',
    );
    _localization.onTranslatedLanguage = _onTranslatedLanguage;
    super.initState();
  }

  void _onTranslatedLanguage(Locale? locale) {
    setState(() {});
  }

  
  Widget build(BuildContext context) {
    return MaterialApp(
      supportedLocales: _localization.supportedLocales,
      localizationsDelegates: _localization.localizationsDelegates,
      home: const HomeScreen(),
    );
  }
}

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

  
  Widget build(BuildContext context) {
    final FlutterLocalization localization = FlutterLocalization.instance;

    return Scaffold(
      appBar: AppBar(
        title: Text(AppLocale.title.getString(context)),
      ),
      body: Padding(
        padding: const EdgeInsets.all(20.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Text(
              AppLocale.welcome.getString(context),
              style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
              textAlign: TextAlign.center,
            ),
            const SizedBox(height: 30),
            Text(
              context.formatString(AppLocale.helloFormat, ['User', 'HarmonyOS']),
              style: const TextStyle(fontSize: 18),
              textAlign: TextAlign.center,
            ),
            const SizedBox(height: 40),
            Text(
              '${AppLocale.currentLanguage.getString(context)}: ${localization.getLanguageName()}',
              style: const TextStyle(fontSize: 16),
            ),
            const SizedBox(height: 20),
            Text(AppLocale.switchLanguage.getString(context)),
            const SizedBox(height: 10),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                ElevatedButton(
                  onPressed: () => localization.translate('en'),
                  child: const Text('English'),
                ),
                const SizedBox(width: 10),
                ElevatedButton(
                  onPressed: () => localization.translate('zh'),
                  child: const Text('中文'),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

7. 总结

Flutter Localization 是一个简洁高效的本地化解决方案,特别适合在鸿蒙平台上开发的 Flutter 应用。它提供了基于 Map 的本地化资源管理、动态语言切换、字符串格式化等功能,API 简洁易用,能够帮助开发者快速实现应用的多语言支持。

通过 Git 方式引入的鸿蒙适配版本,确保了在鸿蒙平台上的稳定运行,同时保持了与原包一致的 API 接口,方便开发者迁移和使用。

欢迎加入开源鸿蒙跨平台社区:https://openharmonycrossplatform.csdn.net

Logo

AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。

更多推荐