Flutter多语言支持插件polyglot_flutter_sdk的使用

Flutter多语言支持插件polyglot_flutter_sdk的使用

开发者指南

开源 我们制作工具以让您的产品支持所有语言。

让开发人员能够直接从代码中创建字符串。

翻译管理系统

团队中所有翻译人员的统一来源。

依托于Google Translate。可以即时部署字符串,快速且简单。

特性

  • 从polyglot API获取本地化字符串。
  • 直接从代码创建字符串 TODO

入门指南

确保在Flutter项目中添加该库作为依赖项:

dependencies:
  polyglot_flutter_sdk: ^0.0.1

示例项目

example文件夹中有一个相当不错的示例项目。查看它。或者继续阅读以了解如何开始使用。

设置

以下是设置项目的示例代码:

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

import 'package:provider/provider.dart';
import 'package:polyglot_flutter_sdk/polyglot_flutter_sdk.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  ///
  /// 初始化polyglot_sdk
  ///
  PolyglotLanguage appLanguage = PolyglotLanguage.instance;
  await appLanguage.init(
      projectUrl:
          'https://d8wlqn7pvlrac.cloudfront.net/c81e728d9d4c2f636f067f89cc14862c/all.json',
      defaultLocale: 'en_US');
  runApp(MyApp(
    appLanguage: appLanguage,
  ));
}

class MyApp extends StatelessWidget {
  final PolyglotLanguage appLanguage;

  MyApp({required this.appLanguage});
  [@override](/user/override)
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<PolyglotLanguage>(
      create: (_) => appLanguage,
      child: Consumer<PolyglotLanguage>(builder: (context, model, child) {
        return MaterialApp(
          // 设置应用语言区域
          locale: model.appLocal,
          title: "POLYGLOT",
          // 添加本地化代理
          localizationsDelegates: [
            const PolyLocalizationsDelegate(),
            GlobalMaterialLocalizations.delegate,
            GlobalWidgetsLocalizations.delegate,
            GlobalCupertinoLocalizations.delegate,
            FallbackLocalizationDelegate(),
          ],
          // 设置支持的语言列表
          supportedLocales: model.suportedLocales,
          home: MyHomePage(title: 'Flutter Demo Home Page'),
        );
      }),
    );
  }
}

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> {
  String? title;
  String? description;
  PolyglotModel? polyModel;

  _MyHomePageState();

  [@override](/user/override)
  Widget build(BuildContext context) {
    var appLanguage = Provider.of<PolyglotLanguage>(context);
    return Scaffold(
      appBar: AppBar(
        title: Text(PolyLocalizations.of(context)?.translate('landing.translationdemo.description') ?? ""),
      ),
      body: Center(
        child: Padding(
          padding: const EdgeInsets.all(12.0),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(
                PolyLocalizations.of(context)?.translate('landing.wemake') ?? "",
                textAlign: TextAlign.justify,
                style: TextStyle(fontSize: 18, color: Colors.red),
              ),
              Text(
                PolyLocalizations.of(context)?.translate('landing.translationdemo.description') ?? "",
                textAlign: TextAlign.center,
                style: TextStyle(fontSize: 18, color: Colors.green),
              ),
              Text(
                PolyLocalizations.of(context)?.translate('landing.backedby') ?? "",
                textAlign: TextAlign.justify,
                style: TextStyle(fontSize: 18, color: Colors.blue[400]),
              ),
              Padding(
                padding: const EdgeInsets.only(top: 20),
                child: Text(
                  PolyLocalizations.of(context)?.translate('landing.copyright') ?? "",
                  textAlign: TextAlign.center,
                  style: TextStyle(fontSize: 18, color: Colors.teal),
                ),
              ),
              Center(
                child: Wrap(
                  children: [
                    for (var lang in appLanguage.localizedStrings!.langs!.keys)
                      Container(
                        margin: const EdgeInsets.all(12),
                        child: TextButton(
                          child: Text('Polyglot $lang'),
                          onPressed: () {
                            print(lang);
                            appLanguage.changeLanguageFromString(lang);
                          },
                        ),
                      )
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

更多关于Flutter多语言支持插件polyglot_flutter_sdk的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter多语言支持插件polyglot_flutter_sdk的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


polyglot_flutter_sdk 是一个用于 Flutter 应用的多语言支持插件。它可以帮助你轻松地在应用中实现多语言支持,并且可以动态加载和管理语言资源。以下是使用 polyglot_flutter_sdk 的基本步骤:

1. 添加依赖

首先,你需要在 pubspec.yaml 文件中添加 polyglot_flutter_sdk 依赖:

dependencies:
  flutter:
    sdk: flutter
  polyglot_flutter_sdk: ^版本号

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

2. 初始化 Polyglot

在你的应用中初始化 Polyglot 实例。通常你可以在 main.dart 文件中进行初始化:

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

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

  // 初始化 Polyglot
  final polyglot = Polyglot(
    defaultLocale: 'en',
    supportedLocales: ['en', 'es', 'fr'],
    localeResolutionCallback: (locale, supportedLocales) {
      // 这里可以自定义语言解析逻辑
      return locale;
    },
  );

  // 加载默认语言资源
  await polyglot.loadLocale('en');

  runApp(MyApp(polyglot: polyglot));
}

class MyApp extends StatelessWidget {
  final Polyglot polyglot;

  MyApp({required this.polyglot});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      locale: polyglot.currentLocale,
      supportedLocales: polyglot.supportedLocales,
      localizationsDelegates: [
        polyglot.localizationsDelegate,
        // 其他本地化代理
      ],
      home: MyHomePage(),
    );
  }
}

3. 加载语言资源

你需要在应用启动时加载默认语言资源,并可以在运行时动态加载其他语言资源:

await polyglot.loadLocale('es'); // 加载西班牙语资源

4. 使用多语言文本

在应用中使用 polyglot 来获取多语言文本:

Text(polyglot.t('hello_world'))

t 方法会根据当前语言环境返回对应的翻译文本。

5. 动态切换语言

你可以在运行时动态切换语言:

await polyglot.setLocale('fr'); // 切换到法语

切换语言后,polyglot 会自动更新应用中的文本。

6. 配置文件

你需要为每种语言创建一个 JSON 文件,例如:

en.json:

{
  "hello_world": "Hello, World!",
  "welcome": "Welcome to our app"
}

es.json:

{
  "hello_world": "¡Hola, Mundo!",
  "welcome": "Bienvenido a nuestra aplicación"
}

这些文件通常放在 assets/locales 目录下,并在 pubspec.yaml 中声明:

flutter:
  assets:
    - assets/locales/en.json
    - assets/locales/es.json
    - assets/locales/fr.json
回到顶部