flutter - 多语言

官网指引
flutter-国际化

1. 设置一个国际化的应用程序: the flutter_localizations package

pubspec.yaml

dependencies:
  flutter:
    sdk: flutter
  flutter_localizations:
    sdk: flutter

2.使用Dart intl工具

a.
pubspec.yaml

dev_dependencies:
  flutter_test:
    sdk: flutter
  intl_translation: ^0.17.2

终端

$ flutter packages get

b.
新建lib/locale/locales.dart
新建lib/l10n/intl_messages.arb

locales.dart

import 'package:intl/intl.dart';

 //testString
  String get testString {
    return Intl.message(
      'Test',
      name: 'testString',
      desc: '测试',
    );
  }

终端

$ flutter packages pub run intl_translation:extract_to_arb --output-dir=lib/l10n lib/locale/locales.dart

lib/l10n/intl_messages.arb 自动编辑为

{
  "@@last_modified": "2019-06-17T14:12:13.366139",
  "testString": "Test",
  "@testString": {
    "description": "测试",
    "type": "text",
    "placeholders": {}
  }
}

c.
创建 lib/l10n/intl_en.arb,lib/l10n/intl_zh.arb, 复制intl_message.arb内容并修改
intl_en.arb

"@@last_modified": "2019-06-17T14:12:13.366139",
  "testString": "Test",
  "@testString": {
    "description": "测试",
    "type": "text",
    "placeholders": {}
  }

intl_zh.arb

"@@last_modified": "2019-06-17T14:12:13.366139",
  "testString": "测试",
  "@testString": {
    "description": "测试",
    "type": "text",
    "placeholders": {}
  }

d.

使用应用程序的根目录作为当前目录,为每个intl_.arb文件生成intl_messages_.dart,并在intl_messages_all.dart中导入所有message文件:

终端

$ flutter packages pub run intl_translation:generate_from_arb --output-dir=lib/l10n \
>    --no-use-deferred-loading lib/l10n/intl_en.arb lib/l10n/intl_zh.arb lib/l10n/intl_messages.arb lib/locale/locales.dart

自动编译生成messages_all.dart,messages_en.dart,messages_messages.dart,messages_zh.dart

e.
修改locales.dart

import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'dart:async';
import 'package:testflutter/l10n/messages_all.dart'; //添加

class AppLocalizations {
  static Future<AppLocalizations> load(Locale locale) {
    final String name = locale.countryCode.isEmpty ? locale.languageCode : locale.toString();
    final String localeName = Intl.canonicalizedLocale(name);
    return initializeMessages(localeName).then((bool _) {
      Intl.defaultLocale = localeName;
      return new AppLocalizations();
    });
  }

  static AppLocalizations of(BuildContext context) {
    return Localizations.of<AppLocalizations>(context, AppLocalizations);
  }
    //testString
  String get testString {
    return Intl.message(
      'Test',
      name: 'testString',
      desc: '测试',
    );
  }
}

class AppLocalizationsDelegate extends LocalizationsDelegate<AppLocalizations> {
  const AppLocalizationsDelegate();

  @override
  bool isSupported(Locale locale) => ['en', 'zh'].contains(locale.languageCode);

  @override
  Future<AppLocalizations> load(Locale locale) {
    return AppLocalizations.load(locale);
  }

  @override
  bool shouldReload(AppLocalizationsDelegate old) => false;
}

f. 引入和使用
main.dart

import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:testflutter/locale/locales.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
      localizationsDelegates: [
        // ... app-specific localization delegate[s] here
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        AppLocalizationsDelegate(), //设置多语言
      ],
      supportedLocales: [
        Locale('zh', 'CH'),
        Locale('en', 'US'),
        // ... other locales the app supports
      ],
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Center(
              child: Text(
                AppLocalizations.of(context).testString, //多语言用法
                style: TextStyle(
                  color: Colors.blue,
                  fontSize: 28.0,
                ),
              ),
            ),
            Container(
              height: 60,
            ),
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.display1,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

效果如下

posted @ 2019-06-17 15:12  gggggggxin  阅读(1802)  评论(0编辑  收藏  举报