Flutter官方国际化方案

1.安装插件

File --> Settings… --> Plugins --> 搜索“flutter Intl”,安装该插件,重启AndroidStudio

2.配置与初始化

  • 配置
    pubspec.yaml文件新增本地化依赖:
dependencies:
    // Other dependencies...
    flutter_localizations:
        sdk: flutter

然后package get获取该依赖

  • 工程初始化
    在菜单栏的Tool下找到Flutter Intl 并选择Initalize for the project,配置结束之后,会自动在 pubspec.yaml中增加以下字段:
flutter_intl:  
    enabled: true

会在lib目录下增加 generated 和 l10n两个包

代码初始化:

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

import 'generated/l10n.dart';

class MyApp extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      localizationsDelegates: const [
        S.delegate,
        GlobalMaterialLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate
      ],
      //supportedLocales: S.delegate.supportedLocales,
      // 设置中文为首选项
      supportedLocales: (<Locale>[const Locale('zh', ''), ])..addAll(S.delegate.supportedLocales),

      // 获取翻译文案的内容需要在能获取到上下文的前提下才能生效,也就是说只能对MaterialApp
      // 的子组件才会生效,所以下面的方法设置动态Title是不行的,需要使用回调方法onGenerateTitle
      //title: S.of(context).app_name,
      onGenerateTitle: (context) => S.of(context).app_name,
      //home: MyHomePage(title: S.of(context).main_message),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

抽取字符串

  • 新建需要支持的语言文件
    在lib/I10n文件夹右键 --> New --> Arb File,输入对应的locale code,如“zh”。
    或者在Tools --> Flutter Intl --> Add Locale,效果是一样的。

  • 抽取字符串
    选中字符串或者在字符串后面按快捷键“Alt + Enter” --> Extract to ARB file
    勾选该字符串要抽取到哪些Arb文件,其实就是在各个arb文件下添加相应的字符串字段,需要到对应的arb文件修改成相应语言的字符串。

使用

在需要配置国际化的地方调用S.of(context).字符串字段即可

一些方法:

# 强制使用某种语言
S.load(Locale('de', 'DE'));

# 获取当前语言
Intl.getCurrentLocale()

参考:
https://plugins.jetbrains.com/plugin/13666-flutter-intl

猜你喜欢

转载自blog.csdn.net/ithouse/article/details/106567502