Flutter本地化管理插件modular_localization的使用

发布于 1周前 作者 nodeper 来自 Flutter

Flutter本地化管理插件modular_localization的使用

modular_localization 是一个用于生成字符串本地化的工具。

开始使用

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

dependencies:
  flutter:
    sdk: flutter
  flutter_localizations:
    sdk: flutter
  modular_localization: ^1.0.0

然后,导入 flutter_localizationsmodular_localization 库,并指定 localizationsDelegatessupportedLocales

import 'package:modular_localization/modular_localization.dart';

return const MaterialApp(
  title: 'Modular Localization Sample App',
  localizationsDelegates: [
    ModularLocalization.delegate,
    GlobalMaterialLocalizations.delegate,
    GlobalWidgetsLocalizations.delegate,
    GlobalCupertinoLocalizations.delegate,
  ],
  supportedLocales: [
    Locale('en', 'US'),
    Locale('pt', 'BR'),
  ],
  home: MyHomePage(),
);

你还可以使用你喜欢的状态管理解决方案来更改应用程序的语言环境,只需在 MaterialApplocale 参数中传递它,并在语言环境改变时重建小部件。

编写本地化字符串文件

接下来,为你的本地化字符串编写 .json 文件:

en-US.json

{
    "greeting": "Hi, would you care for a cup of %s?",
    "drinks": {
        "tea": "tea",
        "coffee": "coffee"
    }
}

pt-BR.json

{
    "greeting": "Olá, gostaria de uma xícara de %s?",
    "drinks": {
        "tea": "chá",
        "coffee": "café"
    }
}

运行

依赖该包后,运行以下命令:

dart run modular_localization [source directory] [target directory]

你可以选择性地指定源目录(默认为 lib/l10n)和目标目录(默认为 lib/l10n/generated),即你的 .json 文件所在的位置和将生成的 .dart 文件存放的位置。

现在,只需导入生成的 ModularLocalization 类并引用生成的本地化字符串:

import 'package:flutter/material.dart';

import '<target directory>/modular_localization.dart';

class MyWidget extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    var drink = ModularLocalization.localizations.drinks.coffee;
    var greeting = ModularLocalization.localizations.greeting([drink]);
    return Text('$greeting $world!'); // 'Olá, gostaria de uma xícara de café?' 或 'Hi, would you care for a cup of coffee?' 取决于设备的目标 Locale。
  }
}

限制

  • 由于 Localizations 小部件的工作方式,由系统语言环境更改触发的语言环境更改可能不会反映在更新的本地化字符串上。
  • 即使你的应用没有任何本地化字符串,你的应用程序也必须支持至少一种语言环境。这意味着需要设置 locale.json 文件。

示例代码

以下是完整的示例代码:

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

import 'l10n/generated/modular_localization.dart';

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

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

  [@override](/user/override)
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  var locale = const Locale('pt', 'BR');

  void updateLocale(Locale locale) {
    setState(() {
      this.locale = locale;
    });
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Modular Localization Sample App',
      locale: locale,
      localizationsDelegates: const [
        ModularLocalization.delegate,
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
      ],
      supportedLocales: const [
        Locale('en', 'US'),
        Locale('pt', 'BR'),
      ],
      home: MyHomePage(
        updateLocale: updateLocale,
      ),
    );
  }
}

class MyHomePage extends StatelessWidget {
  const MyHomePage({
    super.key,
    required this.updateLocale,
  });

  final void Function(Locale) updateLocale;

  [@override](/user/override)
  Widget build(BuildContext context) {
    var drink = ModularLocalization.localizations.drinks.coffee;
    var greeting = ModularLocalization.localizations.greeting([drink]);

    return Scaffold(
      body: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text(greeting),
            ElevatedButton(
              onPressed: () => updateLocale(const Locale('pt', 'BR')),
              child: const Text('pt-BR'),
            ),
            ElevatedButton(
              onPressed: () => updateLocale(const Locale('en', 'US')),
              child: const Text('en-US'),
            ),
          ],
        ),
      ),
    );
  }
}

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

1 回复

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


当然,关于Flutter本地化管理插件modular_localization的使用,下面是一个详细的代码案例来展示如何集成和使用该插件。

1. 添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  modular_localization: ^x.y.z  # 请替换为最新版本号
  flutter_localizations:
    sdk: flutter

2. 创建语言文件

assets目录下创建一个locales文件夹,并在其中创建对应的语言文件,比如en.jsonzh.json

// assets/locales/en.json
{
  "welcome": "Welcome",
  "goodbye": "Goodbye"
}

// assets/locales/zh.json
{
  "welcome": "欢迎",
  "goodbye": "再见"
}

3. 配置pubspec.yaml

pubspec.yaml中配置资源文件:

flutter:
  assets:
    - assets/locales/en.json
    - assets/locales/zh.json

4. 设置MaterialApp的本地化

在你的main.dart文件中,使用ModularApp并配置本地化:

import 'package:flutter/material.dart';
import 'package:flutter_modular/flutter_modular.dart';
import 'package:modular_localization/modular_localization.dart';

void main() {
  runApp(ModularApp(
    module: AppModule(),
    child: MaterialApp(
      title: 'Modular Localization Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      localizationsDelegates: [
        // 添加ModularLocalizationsDelegate
        ModularLocalizationsDelegate(),
        // 添加GlobalMaterialLocalizations和其他必要的本地化委托
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
      ],
      supportedLocales: [
        Locale('en', ''),
        Locale('zh', ''),
      ],
      localeResolutionCallback: (locale, supportedLocales) {
        // 根据需要自定义本地化解析逻辑
        for (var supportedLocale in supportedLocales) {
          if (supportedLocale.languageCode == locale?.languageCode ||
              supportedLocale.countryCode == locale?.countryCode) {
            return supportedLocale;
          }
        }
        return supportedLocales.first;
      },
      home: HomePage(),
    ),
  ));
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    final ModularLocalizations localizations = ModularLocalizations.of(context)!;
    return Scaffold(
      appBar: AppBar(
        title: Text(localizations.translate('welcome')),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(localizations.translate('welcome')),
            ElevatedButton(
              onPressed: () {
                Modular.to.pushNamed('/change_language');
              },
              child: Text(localizations.translate('change_language')), // 假设你有一个改变语言的路由
            ),
          ],
        ),
      ),
    );
  }
}

5. 配置路由和模块

创建一个模块文件app_module.dart,并配置路由:

import 'package:flutter_modular/flutter_modular.dart';
import 'home_page.dart';
import 'change_language_page.dart';

class AppModule extends Module {
  @override
  final List<Bind> binds = [];

  @override
  final List<ModularRoute> routes = [
    ModularRoute('/', child: (context, args) => HomePage()),
    ModularRoute('/change_language', child: (context, args) => ChangeLanguagePage()),
  ];
}

6. 创建改变语言的页面

创建一个change_language_page.dart文件,用于切换语言:

import 'package:flutter/material.dart';
import 'package:flutter_modular/flutter_modular.dart';
import 'package:modular_localization/modular_localization.dart';

class ChangeLanguagePage extends StatefulWidget {
  @override
  _ChangeLanguagePageState createState() => _ChangeLanguagePageState();
}

class _ChangeLanguagePageState extends State<ChangeLanguagePage> {
  Locale? _selectedLocale;

  @override
  Widget build(BuildContext context) {
    final ModularLocalizations localizations = ModularLocalizations.of(context)!;
    return Scaffold(
      appBar: AppBar(
        title: Text(localizations.translate('change_language')),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            DropdownButton<Locale>(
              value: _selectedLocale,
              hint: Text(localizations.translate('select_language')),
              onChanged: (Locale? newValue) {
                setState(() {
                  _selectedLocale = newValue;
                  Modular.get<ModularLocalizations>().changeLocale(_selectedLocale!);
                  Modular.to.pop();
                });
              },
              items: [
                DropdownMenuItem<Locale>(
                  value: Locale('en', ''),
                  child: Text('English'),
                ),
                DropdownMenuItem<Locale>(
                  value: Locale('zh', ''),
                  child: Text('中文'),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

7. 运行应用

现在,你可以运行你的Flutter应用,并看到本地化已经生效。你可以通过点击按钮跳转到ChangeLanguagePage页面来选择语言,选择后应用的语言将会切换。

这个示例展示了如何使用modular_localization插件来管理Flutter应用的本地化。注意,实际项目中可能需要更多的配置和优化,比如持久化用户选择的语言等。

回到顶部