Flutter国际化的三种方式-->flutter-i18n


1. 安装Flutter i18n

Flutter i18n是一个Android Studio的插件。没有安装的需要进行安装,如下图所示。



安装后项目的结构如下图所示:


res/values/strings_en.arb和lib/generated/i18n.dart是自动生成的。

2.在res/values目录下添加strings_zh.arb

strings后面跟的zh必须是Locale的languageCode。添加完成之后分别在strings_en.arb和strings_zh.arb中添加你要国际化的属性,如下所示:

{
  "hello": "你好!",
  "greetTo": " $name,见到你非常高兴!"
}
{
  "hello": "Hello!",
  "greetTo": "Nice to meet you, $name!"
}

从上面,我们发现flutter i18n插件比起intl方法,帮我们省了很多东西,我们只需要关注要国际化的属性即可,不在需要关注生成arb文件和arb文件再生成dart这些步骤。

3. 在main中的使用

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

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State {
  String _locale = 'zh';
  onChangeLanguage() {
    if (_locale == 'en') {
      setState(() {
        _locale = 'zh';
      });
    } else {
      setState(() {
        _locale = 'en';
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
        locale: Locale(_locale, ""),
        localizationsDelegates: [
          S.delegate,
          GlobalMaterialLocalizations.delegate,
          GlobalWidgetsLocalizations.delegate,
          GlobalCupertinoLocalizations.delegate,
        ],
        supportedLocales: S.delegate.supportedLocales,
        localeResolutionCallback:
            S.delegate.resolution(fallback: new Locale('zh', '')),
        home: MyHomePage(this.onChangeLanguage));
  }
}

class MyHomePage extends StatelessWidget {
  final VoidCallback onChangeLanguage;
  MyHomePage(this.onChangeLanguage);

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
        appBar: new AppBar(
          title: new Text(S.of(context).hello),
        ),
        body: new Center(
          child: new Text(S.of(context).greetTo('Nina')),
        ),
        floatingActionButton: new FloatingActionButton(
            child: new Icon(Icons.language), onPressed: onChangeLanguage));
  }
}

你可能感兴趣的:(Flutter国际化的三种方式-->flutter-i18n)