flutter - 多語言

官網指引
flutter-國際化app

1. 設置一個國際化的應用程序: the flutter_localizations package

pubspec.yamlless

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

2.使用Dart intl工具

a.
pubspec.yamlasync

dev_dependencies:
  flutter_test:
    sdk: flutter
  intl_translation: ^0.17.2

終端ide

$ 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: '測試',
    );
  }

終端ui

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

lib/l10n/intl_messages.arb 自動編輯爲this

{
  "@@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.arbcode

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

intl_zh.arbblog

"@@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),
      ),
    );
  }
}

效果以下

相關文章
相關標籤/搜索