Flutter语言翻译插件codebase_translate的使用
Flutter语言翻译插件codebase_translate的使用
简介
codebase_translate 是一个功能强大的 Flutter 定位/国际化库,支持多语言切换。它允许你为不同的语言定义翻译,并轻松在它们之间切换。

特性
- 非常易于使用
 - 支持移动端、Web 和桌面端
 - 支持复数和双数
 - 支持 
languageCode(如en)和languageCode_countryCode(如en_US)格式 - 自动保存和恢复所选的语言环境
 - 完全支持右到左语言
 - 提供回退语言环境的支持
 - 支持内联或嵌套 JSON
 
示例
效果图

使用步骤
1. 添加依赖
在 pubspec.yaml 文件中添加以下依赖:
dependencies:
  codebase_translate: ^版本号
然后运行 flutter pub get。
2. 初始化并配置
在 main.dart 中初始化并配置 LocalizationDelegate:
import 'package:codebase_translate/codebase_translate.dart';
import 'package:flutter/material.dart';
void main() async {
  // 创建 LocalizationDelegate
  var delegate = await LocalizationDelegate.create(
      fallbackLocale: 'en_US', // 设置默认语言
      supportedLocales: ['en_US', 'es', 'fa', 'ar', 'ru']); // 支持的语言列表
  // 启动应用
  runApp(LocalizedApp(delegate, MyApp()));
}
3. 配置 Material App
在 MyApp 中配置 MaterialApp,并将 LocalizationDelegate 添加到 localizationsDelegates 中:
class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    var localizationDelegate = LocalizedApp.of(context).delegate;
    return LocalizationProvider(
      state: LocalizationProvider.of(context).state,
      child: MaterialApp(
        title: 'Flutter Translate Demo',
        localizationsDelegates: [
          GlobalMaterialLocalizations.delegate,
          GlobalWidgetsLocalizations.delegate,
          localizationDelegate // 添加本地化代理
        ],
        supportedLocales: localizationDelegate.supportedLocales, // 支持的语言列表
        locale: localizationDelegate.currentLocale, // 当前语言环境
        theme: ThemeData(primarySwatch: Colors.blue),
        home: MyHomePage(),
      ),
    );
  }
}
4. 创建 Home 页面
在 MyHomePage 中实现语言切换和多语言支持:
class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, this.title}) : super(key: key);
  final String? title;
  [@override](/user/override)
  _MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  void _decrementCounter() => setState(() => _counter--);
  void _incrementCounter() => setState(() => _counter++);
  [@override](/user/override)
  Widget build(BuildContext context) {
    var localizationDelegate = LocalizedApp.of(context).delegate;
    return Scaffold(
      appBar: AppBar(
        title: Text(translate('app_bar.title')), // 使用翻译函数
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            // 显示当前选择的语言
            Text(translate('language.selected_message', args: {
              'language': translate(
                  'language.name.${localizationDelegate.currentLocale.languageCode}')
            })),
            // 按钮用于切换语言
            Padding(
                padding: EdgeInsets.only(top: 25, bottom: 160),
                child: CupertinoButton.filled(
                  child: Text(translate('button.change_language')),
                  padding: const EdgeInsets.symmetric(
                      vertical: 10.0, horizontal: 36.0),
                  onPressed: () => _onActionSheetPress(context),
                )),
            // 复数支持示例
            Padding(
                padding: const EdgeInsets.only(bottom: 10),
                child: Text(translatePlural('plural.demo', _counter))),
            // 增减计数器按钮
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                IconButton(
                  icon: Icon(Icons.remove_circle),
                  iconSize: 48,
                  onPressed: _counter > 0
                      ? () => setState(() => _decrementCounter())
                      : null,
                ),
                IconButton(
                  icon: Icon(Icons.add_circle),
                  color: Colors.blue,
                  iconSize: 48,
                  onPressed: () => setState(() => _incrementCounter()),
                ),
              ],
            )
          ],
        ),
      ),
    );
  }
  // 显示语言选择弹窗
  void showDemoActionSheet(
      {required BuildContext context, required Widget child}) {
    showCupertinoModalPopup<String>(
        context: context,
        builder: (BuildContext context) => child).then((String? value) {
      if (value != null) changeLocale(context, value);
    });
  }
  // 处理语言切换按钮点击事件
  void _onActionSheetPress(BuildContext context) {
    showDemoActionSheet(
      context: context,
      child: CupertinoActionSheet(
        title: Text(translate('language.selection.title')),
        message: Text(translate('language.selection.message')),
        actions: <Widget>[
          CupertinoActionSheetAction(
            child: Text(translate('language.name.en')),
            onPressed: () => Navigator.pop(context, 'en_US'),
          ),
          CupertinoActionSheetAction(
            child: Text(translate('language.name.es')),
            onPressed: () => Navigator.pop(context, 'es'),
          ),
          CupertinoActionSheetAction(
            child: Text(translate('language.name.ar')),
            onPressed: () => Navigator.pop(context, 'ar'),
          ),
          CupertinoActionSheetAction(
            child: Text(translate('language.name.ru')),
            onPressed: () => Navigator.pop(context, 'ru'),
          ),
        ],
        cancelButton: CupertinoActionSheetAction(
          child: Text(translate('button.cancel')),
          isDefaultAction: true,
          onPressed: () => Navigator.pop(context, null),
        ),
      ),
    );
  }
}
更多关于Flutter语言翻译插件codebase_translate的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter语言翻译插件codebase_translate的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
codebase_translate 是一个用于 Flutter 项目的翻译管理插件。它可以帮助你自动化地从代码中提取需要翻译的字符串,并生成翻译文件。以下是如何使用 codebase_translate 插件的基本步骤:
1. 添加依赖
首先,你需要在 pubspec.yaml 文件中添加 codebase_translate 插件的依赖:
dependencies:
  flutter:
    sdk: flutter
dev_dependencies:
  codebase_translate: ^1.0.0  # 请确保使用最新版本
然后运行 flutter pub get 来安装依赖。
2. 配置 codebase_translate
在项目的根目录下创建一个 codebase_translate.yaml 配置文件。这个文件用于指定插件的配置选项。以下是一个示例配置:
input_dirs:
  - lib
output_dir: lib/l10n
locales:
  - en
  - es
  - fr
default_locale: en
arb_file: app_localizations.arb
input_dirs: 指定需要扫描的目录,通常是lib目录。output_dir: 指定生成的翻译文件的输出目录。locales: 指定支持的语言代码列表。default_locale: 指定默认的语言代码。arb_file: 指定生成的.arb文件的名称。
3. 在代码中使用翻译字符串
在你的 Flutter 代码中,你可以使用 codebase_translate 提供的 tr 方法来标记需要翻译的字符串:
import 'package:flutter/material.dart';
import 'package:codebase_translate/codebase_translate.dart';
void main() {
  runApp(MyApp());
}
class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text(tr('Hello, World!')),
        ),
        body: Center(
          child: Text(tr('Welcome to Flutter')),
        ),
      ),
    );
  }
}
4. 提取翻译字符串
在终端中运行以下命令,从代码中提取需要翻译的字符串并生成 .arb 文件:
flutter pub run codebase_translate:extract
这将在 output_dir 指定的目录下生成一个 .arb 文件,其中包含所有需要翻译的字符串。
5. 翻译字符串
打开生成的 .arb 文件,将字符串翻译成不同的语言。例如:
{
  "@@locale": "en",
  "Hello, World!": "Hello, World!",
  "Welcome to Flutter": "Welcome to Flutter"
}
{
  "@@locale": "es",
  "Hello, World!": "¡Hola, Mundo!",
  "Welcome to Flutter": "Bienvenido a Flutter"
}
{
  "@@locale": "fr",
  "Hello, World!": "Bonjour, le Monde!",
  "Welcome to Flutter": "Bienvenue à Flutter"
}
6. 生成 Dart 代码
翻译完成后,运行以下命令生成 Dart 代码:
flutter pub run codebase_translate:generate
这将在 output_dir 指定的目录下生成 Dart 文件,其中包含翻译的字符串。
7. 在应用中使用生成的翻译
生成的 Dart 文件通常包含一个 AppLocalizations 类,你可以在应用中使用它来获取翻译后的字符串:
import 'package:flutter/material.dart';
import 'generated/l10n.dart';
void main() {
  runApp(MyApp());
}
class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      localizationsDelegates: AppLocalizations.localizationsDelegates,
      supportedLocales: AppLocalizations.supportedLocales,
      home: Scaffold(
        appBar: AppBar(
          title: Text(AppLocalizations.of(context)!.helloWorld),
        ),
        body: Center(
          child: Text(AppLocalizations.of(context)!.welcomeToFlutter),
        ),
      ),
    );
  }
}
        
      
            
            
            
