Flutter本地化注解插件utopia_localization_annotation的使用

Flutter本地化注解插件 utopia_localization_annotation 的使用

utopia_localization_annotation 是一个用于生成国际化资源文件的注解库,它与 utopia_localization_generator 配合使用,可以轻松实现 Flutter 应用的多语言支持。


安装依赖

pubspec.yaml 文件中添加以下依赖:

dependencies:
  utopia_localization_annotation: ^版本号

dev_dependencies:
  build_runner: ^版本号
  utopia_localization_generator: ^版本号

运行 flutter pub get 安装依赖。


使用步骤

  1. 创建注解类

    创建一个类并使用 [@Localization](/user/Localization) 注解来定义需要本地化的字符串。

    import 'package:utopia_localization_annotation/utopia_localization_annotation.dart';
    
    [@Localization](/user/Localization)(
      domain: 'app', // 国际化域,用于区分不同模块
      locales: ['en', 'zh'], // 支持的语言
    )
    abstract class AppLocalizations {
      static const locale = Locale('en'); // 默认语言
    
      [@StringKey](/user/StringKey)('hello_world') // 定义键值对
      String helloWorld();
    
      [@StringKey](/user/StringKey)('goodbye') // 定义键值对
      String goodbye();
    }
    
  2. 生成资源文件

    运行以下命令生成资源文件:

    flutter pub run build_runner build
    

    生成的文件将包含 AppLocalizations 类的具体实现,并生成对应的 .arb 文件(JSON 格式的国际化文件)。

  3. 编写本地化内容

    在生成的 .arb 文件中填写具体的翻译内容。例如:

    {
      "@ar": {},
      "hello_world": "Hello World",
      "goodbye": "Goodbye"
    }
    

    对于其他语言,如中文:

    {
      "@ar": {},
      "hello_world": "你好,世界",
      "goodbye": "再见"
    }
    
  4. 加载本地化资源

    在应用中使用 AppLocalizations 加载本地化资源:

    import 'package:flutter/material.dart';
    import 'generated/app_localizations.g.dart'; // 导入生成的类
    
    void main() {
      runApp(MyApp());
    }
    
    class MyApp extends StatelessWidget {
      [@override](/user/override)
      Widget build(BuildContext context) {
        return MaterialApp(
          localizationsDelegates: [
            AppLocalizations.delegate, // 添加本地化代理
          ],
          supportedLocales: AppLocalizations.supportedLocales, // 支持的语言
          home: MyHomePage(),
        );
      }
    }
    
    class MyHomePage extends StatelessWidget {
      [@override](/user/override)
      Widget build(BuildContext context) {
        final localizations = AppLocalizations.of(context)!; // 获取本地化实例
    
        return Scaffold(
          appBar: AppBar(
            title: Text(localizations.helloWorld()), // 使用本地化字符串
          ),
          body: Center(
            child: Text(localizations.goodbye()), // 使用本地化字符串
          ),
        );
      }
    }
    

完整示例

以下是完整的代码示例,展示如何使用 utopia_localization_annotation 实现多语言支持:

import 'package:flutter/material.dart';
import 'package:utopia_localization_annotation/utopia_localization_annotation.dart';
import 'generated/app_localizations.g.dart'; // 导入生成的类

// 定义本地化注解类
[@Localization](/user/Localization)(
  domain: 'app',
  locales: ['en', 'zh'],
)
abstract class AppLocalizations {
  static const locale = Locale('en');

  [@StringKey](/user/StringKey)('hello_world')
  String helloWorld();

  [@StringKey](/user/StringKey)('goodbye')
  String goodbye();
}

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

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

class MyHomePage extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    final localizations = AppLocalizations.of(context)!;

    return Scaffold(
      appBar: AppBar(
        title: Text(localizations.helloWorld()),
      ),
      body: Center(
        child: Text(localizations.goodbye()),
      ),
    );
  }
}

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

1 回复

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


utopia_localization_annotation 是一个用于 Flutter 应用的本地化注解插件,它可以帮助开发者更方便地管理和生成本地化字符串。通过使用注解,开发者可以在代码中直接标记需要本地化的字符串,然后通过工具生成对应的本地化文件。

以下是 utopia_localization_annotation 的基本使用步骤:

1. 添加依赖

首先,在 pubspec.yaml 文件中添加 utopia_localization_annotationutopia_localization_generator 依赖:

dependencies:
  flutter:
    sdk: flutter
  utopia_localization_annotation: ^1.0.0

dev_dependencies:
  build_runner: ^2.1.0
  utopia_localization_generator: ^1.0.0

2. 创建本地化类

接下来,创建一个类并使用 @Localization 注解来标记需要本地化的字符串。例如:

import 'package:utopia_localization_annotation/utopia_localization_annotation.dart';

part 'localizations.g.dart'; // 生成的代码文件

@Localization()
class AppLocalizations {
  @LocalizationString("Hello, world!")
  String get helloWorld;

  @LocalizationString("Welcome, {name}!")
  String welcome(String name);
}

3. 生成本地化文件

使用 build_runner 生成本地化文件。在终端中运行以下命令:

flutter pub run build_runner build

这将生成一个 localizations.g.dart 文件,其中包含了本地化的实现。

4. 使用本地化字符串

在应用中,你可以通过 AppLocalizations 类来获取本地化字符串。例如:

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Localization Example'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(AppLocalizations.of(context).helloWorld),
              Text(AppLocalizations.of(context).welcome('John')),
            ],
          ),
        ),
      ),
    );
  }
}

5. 配置本地化支持

确保在 MaterialAppCupertinoApp 中配置了本地化支持:

import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'localizations.dart';

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      localizationsDelegates: [
        AppLocalizations.delegate,
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
      ],
      supportedLocales: [
        const Locale('en', ''),
        const Locale('zh', 'CN'),
      ],
      home: MyHomePage(),
    );
  }
}

6. 添加翻译文件

lib/l10n 目录下创建对应的翻译文件,例如 app_en.arbapp_zh_CN.arb

app_en.arb:

{
  "helloWorld": "Hello, world!",
  "welcome": "Welcome, {name}!"
}

app_zh_CN.arb:

{
  "helloWorld": "你好,世界!",
  "welcome": "欢迎, {name}!"
}

7. 重新生成代码

每次修改了翻译文件后,重新运行 build_runner 以更新生成的代码。

flutter pub run build_runner build
回到顶部