Flutter本地化工具插件utopia_localization_utils的使用

Flutter本地化工具插件utopia_localization_utils的使用

utopia_localization_utils 是一个用于 Flutter 应用本地化的实用工具库。它与 utopia_localization_generator 配合使用,可以简化多语言支持的实现。


使用步骤

以下是一个完整的示例,展示如何在 Flutter 项目中使用 utopia_localization_utils 插件。


1. 添加依赖

首先,在项目的 pubspec.yaml 文件中添加 utopia_localization_utilsutopia_localization_generator 作为依赖:

dependencies:
  utopia_localization_utils: ^x.x.x  # 替换为最新版本号

dev_dependencies:
  utopia_localization_generator: ^x.x.x  # 替换为最新版本号

运行以下命令以安装依赖:

flutter pub get

2. 创建本地化文件

创建一个本地化文件(例如 app_messages.dart),并在其中定义本地化的字符串。

// app_messages.dart
import 'package:utopia_localization_utils/utopia_localization_utils.dart';

part 'app_messages.g.dart'; // 自动生成的文件

@UtopiaMessages()
class AppMessages extends Messages {
  [@override](/user/override)
  String get appName => '我的应用';

  [@override](/user/override)
  String get welcomeMessage => '欢迎使用 {appName}';

  [@override](/user/override)
  String get buttonLabel => '点击我';
}

3. 生成本地化代码

运行 utopia_localization_generator 工具以生成本地化代码。确保你已经配置好生成器脚本。

flutter packages pub run build_runner build --delete-conflicting-outputs

这将在 app_messages.dart 的同一目录下生成 app_messages.g.dart 文件。


4. 初始化本地化工具

main.dart 中初始化 utopia_localization_utils,并设置默认的语言环境。

// main.dart
import 'package:flutter/material.dart';
import 'package:utopia_localization_utils/utopia_localization_utils.dart';
import 'app_messages.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  // 设置默认语言
  await UtopiaLocalization.init(
    defaultLocale: const Locale('zh', 'CN'), // 默认语言为中文
    supportedLocales: [
      const Locale('zh', 'CN'),
      const Locale('en', 'US'),
    ],
    messages: AppMessages(),
  );

  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      localizationsDelegates: UtopiaLocalization.localizationsDelegates,
      supportedLocales: UtopiaLocalization.supportedLocales,
      home: HomePage(),
    );
  }
}

5. 使用本地化字符串

在需要的地方使用 translate 方法来获取本地化的字符串。

// home_page.dart
import 'package:flutter/material.dart';
import 'package:utopia_localization_utils/utopia_localization_utils.dart';

class HomePage extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(translate('appName')),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(translate('welcomeMessage')),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: () {},
              child: Text(translate('buttonLabel')),
            ),
          ],
        ),
      ),
    );
  }
}

完整示例代码

以下是完整的代码示例:

// main.dart
import 'package:flutter/material.dart';
import 'package:utopia_localization_utils/utopia_localization_utils.dart';
import 'app_messages.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  // 设置默认语言
  await UtopiaLocalization.init(
    defaultLocale: const Locale('zh', 'CN'),
    supportedLocales: [
      const Locale('zh', 'CN'),
      const Locale('en', 'US'),
    ],
    messages: AppMessages(),
  );

  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      localizationsDelegates: UtopiaLocalization.localizationsDelegates,
      supportedLocales: UtopiaLocalization.supportedLocales,
      home: HomePage(),
    );
  }
}

// home_page.dart
import 'package:flutter/material.dart';
import 'package:utopia_localization_utils/utopia_localization_utils.dart';

class HomePage extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(translate('appName')),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(translate('welcomeMessage')),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: () {},
              child: Text(translate('buttonLabel')),
            ),
          ],
        ),
      ),
    );
  }
}

更多关于Flutter本地化工具插件utopia_localization_utils的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter本地化工具插件utopia_localization_utils的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


utopia_localization_utils 是一个用于 Flutter 应用程序的本地化工具插件,它可以帮助开发者更轻松地管理和实现应用程序的多语言支持。以下是如何使用 utopia_localization_utils 的基本步骤:

1. 安装插件

首先,在 pubspec.yaml 文件中添加 utopia_localization_utils 插件的依赖:

dependencies:
  flutter:
    sdk: flutter
  utopia_localization_utils: ^1.0.0  # 请使用最新版本

然后运行 flutter pub get 来安装依赖。

2. 创建本地化文件

在项目中创建一个文件夹(例如 lib/l10n),用于存放不同语言的 JSON 文件。每个 JSON 文件对应一种语言,文件名通常使用语言代码(如 en.json, zh.json 等)。

例如,en.json 文件内容可能如下:

{
  "hello": "Hello",
  "welcome": "Welcome to Flutter"
}

zh.json 文件内容可能如下:

{
  "hello": "你好",
  "welcome": "欢迎使用 Flutter"
}

3. 配置本地化工具

main.dart 文件中配置 utopia_localization_utils 插件。首先,导入插件:

import 'package:utopia_localization_utils/utopia_localization_utils.dart';

然后在 main 函数中初始化本地化工具:

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  await UtopiaLocalizationUtils.initialize(
    supportedLocales: [
      const Locale('en', 'US'),
      const Locale('zh', 'CN'),
    ],
    defaultLocale: const Locale('en', 'US'),
    assetPath: 'lib/l10n',
  );

  runApp(MyApp());
}

4. 使用本地化字符串

在应用程序中使用 UtopiaLocalizationUtils 来获取本地化字符串。例如:

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      localizationsDelegates: UtopiaLocalizationUtils.localizationsDelegates,
      supportedLocales: UtopiaLocalizationUtils.supportedLocales,
      locale: UtopiaLocalizationUtils.locale,
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(UtopiaLocalizationUtils.of(context).getString('welcome')),
      ),
      body: Center(
        child: Text(UtopiaLocalizationUtils.of(context).getString('hello')),
      ),
    );
  }
}

5. 动态切换语言

utopia_localization_utils 还提供了动态切换语言的功能。你可以通过以下代码来切换语言:

UtopiaLocalizationUtils.setLocale(const Locale('zh', 'CN'));

6. 处理缺失的翻译

如果某个键在当前的本地化文件中没有找到对应的翻译,utopia_localization_utils 可以返回一个默认值或抛出异常。你可以在初始化时配置这种行为:

await UtopiaLocalizationUtils.initialize(
  supportedLocales: [
    const Locale('en', 'US'),
    const Locale('zh', 'CN'),
  ],
  defaultLocale: const Locale('en', 'US'),
  assetPath: 'lib/l10n',
  onMissingTranslation: (key) {
    return '[$key]';  // 返回默认值
  },
);
回到顶部