Flutter 中的國(guó)際化

一痹愚、前言

從 2015 年接觸 Flutter 到現(xiàn)在也有兩年多時(shí)間排霉,在這期間我并沒有正真地去了解這個(gè)神奇的框架,只是時(shí)不時(shí)拉取 master 的最新代碼距芬,編一下 flutter_gallery 看看有什么新特性罩驻。但隨著此次 GDD 的召開穗酥,F(xiàn)lutter 被 Google 帶到了國(guó)內(nèi)開發(fā)者的眼前,相信谷歌是已經(jīng)準(zhǔn)備好讓 Flutter 走上移動(dòng)開發(fā)歷史的舞臺(tái)了。

一款好的移動(dòng)應(yīng)用該具備什么品質(zhì)迷扇?戳中用戶痛點(diǎn)的功能百揭,炫酷的 UI 還是流暢的操作體驗(yàn)?這些都很重要蜓席,少了其中任何一點(diǎn)都是得不到用戶青睞的。但今天我要說的雖然不是前面這三個(gè)中的哪一個(gè)课锌,但也是少了它就不行的“應(yīng)用國(guó)際化”厨内。

對(duì)于開發(fā)者來說,在 Android 和 iOS 開發(fā)中使用國(guó)際化已經(jīng)是老掉牙的套路了渺贤,那么在 Flutter 中該如何使用國(guó)際化呢雏胃?是否也想 Android 一樣只要多配置一個(gè) xml 就能搞定了呢?

二志鞍、在 MaterialApp 中添加國(guó)際化支持

Flutter 官方鼓勵(lì)我們?cè)趯?Flutter 應(yīng)用的時(shí)候直接從 MaterialApp 開始瞭亮,原因是 MaterialApp 為我們集成好了很多 Material Design 所必須的控件,如AnimatedThemen固棚、GridPager 等统翩,另外還通過 MaterialApp 配置了全局路由,方便進(jìn)行頁面的切換此洲。既然如此我們就先從 MaterialApp 開始實(shí)現(xiàn)國(guó)際化厂汗。國(guó)際化涵蓋的不單單只是多國(guó)語言,還有文字閱讀方向呜师、時(shí)間和日期格式等娶桦,但本文僅介紹多國(guó)語言的適配,它們幾種還希望讀者自行學(xué)習(xí)和研究汁汗。

通常我們新建的 Flutter 應(yīng)用是默認(rèn)不支持多語言的衷畦,即使用戶在中文環(huán)境下,顯示的文字仍然是英文知牌,比如下圖所示的日期選擇對(duì)話框:

image

那么怎么樣將系統(tǒng)的這些組件國(guó)際化呢祈争?首先需要在 pubspec.yaml 中添加如下依賴:

  flutter_localizations:
    sdk: flutter

接著運(yùn)行:

flutter packages get

以獲取依賴庫。

當(dāng)上面兩部完成后在 main.dart 中 import 如下:

import 'package:flutter_localizations/flutter_localizations.dart';

然后在 MaterialApp 的構(gòu)造方法中給 localizationsDelegatessupportedLocales 兩個(gè)可選參數(shù)賦值:

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new MyHomePage(title: 'Flutter Demo Home Page'),
      localizationsDelegates: [                             //此處
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
      ],
      supportedLocales: [                                   //此處
        const Locale('zh','CH'),
        const Locale('en','US'),
      ],
    );
  }
}

暫時(shí)先不用理解這兩個(gè)參數(shù)是什么意思送爸,此時(shí)如果重新運(yùn)行的話結(jié)果如下圖:

image

細(xì)心的小伙伴可能發(fā)現(xiàn)這個(gè) Dialog 中的文字是變成中文了铛嘱,但背景中的 titlebar 的文字還是英文,難道老司機(jī)也翻車了袭厂?

其實(shí) titlebar 中的這串文字是屬于我們創(chuàng)建的應(yīng)用的墨吓,如下:

home: new MyHomePage(title: 'Flutter Demo Home Page')

Flutter 框架是不知道翻譯這句話。

接下來要做的就是我們自己實(shí)現(xiàn)一個(gè)類似 GlobalMaterialLocalizations的東西纹磺,用它來實(shí)現(xiàn)多語言帖烘。

首先需要準(zhǔn)備在應(yīng)用中用到的字符串,一個(gè)剛新建的 Flutter 應(yīng)用用到了四個(gè)字符串橄杨,如下

  • Flutter Demo
  • Flutter Demo Home Page
  • You have pushed the button this many times:
  • Increment

這里為了簡(jiǎn)單我們只增加中文秘症,依次對(duì)應(yīng)為:

  • Flutter 示例
  • Flutter 示例主頁面
  • 你一共點(diǎn)擊了這么多次按鈕:
  • 增加

兩種文字準(zhǔn)備后就可以著手寫 Localizations 了照卦,此處的 Localizations 是多國(guó)語言資源的匯總。在這里我自定義一個(gè)名為 DemoLocalizations 的類,然后將多國(guó)資源整合進(jìn)此類:

class DemoLocalizations {

  final Locale locale;

  DemoLocalizations(this.locale);

  static Map<String, Map<String, String>> _localizedValues = {
    'en': {
      'task title': 'Flutter Demo',
      'titlebar title': 'Flutter Demo Home Page',
      'click tip': 'You have pushed the button this many times:',
      'inc':'Increment'
    },
    'zh': {
      'task title': 'Flutter 示例',
      'titlebar title': 'Flutter 示例主頁面',
      'click tip': '你一共點(diǎn)擊了這么多次按鈕:',
      'inc':'增加'
    }
  };

  get taskTitle{
    return _localizedValues[locale.languageCode]['task title'];
  }

  get titleBarTitle{
    return _localizedValues[locale.languageCode]['titlebar title'];
  }

  get clickTop{
    return _localizedValues[locale.languageCode]['click tip'];
  }
  
  get inc{
    return _localizedValues[locale.languageCode]['inc'];
  }
}

此時(shí)只要能拿到 DemoLocalizations 的對(duì)象實(shí)例乡摹,就可以調(diào)用它的taskTitle役耕、titleBarTitleclickTop這三個(gè)方法來獲取對(duì)應(yīng)的字符串聪廉。

定義完 DemoLocalizations 以后瞬痘,我們就需要想這么一個(gè)問題,這個(gè)類是誰負(fù)責(zé)初始化呢板熊?答案自然不是我們自己主動(dòng)去初始化框全,而是需要一個(gè)叫做 LocalizationsDelegate的類來完成,LocalizationsDelegate 是一個(gè)抽象類干签,需要我們?nèi)?shí)現(xiàn)它:

class DemoLocalizationsDelegate extends LocalizationsDelegate<DemoLocalizations>{

  const DemoLocalizationsDelegate();

  @override
  bool isSupported(Locale locale) {
    return ['en','zh'].contains(locale.languageCode);
  }

  @override
  Future<DemoLocalizations> load(Locale locale) {
    return new SynchronousFuture<DemoLocalizations>(new DemoLocalizations(locale));
  }

  @override
  bool shouldReload(LocalizationsDelegate<DemoLocalizations> old) {
    return false;
  }

  static DemoLocalizationsDelegate delegate = const DemoLocalizationsDelegate();
}

注意 load 方法津辩,DemoLocalizations就是在此方法內(nèi)被初始化的。

接著將 DemoLocalizationsDelegate 添加進(jìn) MaterialApp:

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new MyHomePage(title: 'Flutter Demo Home Page'),
      localizationsDelegates: [
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        DemoLocalizationsDelegate.delegate,                 //添加在此處
      ],
      supportedLocales: [
        const Locale('zh', 'CH'),
        const Locale('en', 'US'),
      ],
    );
  }
}

DemoLocalizationsDelegate 已經(jīng)被添加進(jìn) MaterialApp容劳,那我們?cè)撊绾问褂?DemoLocalizations 呢喘沿?這里就要介紹另一個(gè) Weidget 的子類 Localizations,注意此處的 Localizations 它是一個(gè)貨真價(jià)實(shí) Widget鸭蛙。DemoLocalizationsDelegate 這個(gè)類的對(duì)象雖然被傳入了 MaterialApp摹恨,但由于 MaterialApp 會(huì)在內(nèi)部嵌套 Localizations 這個(gè) Widget,而 LocalizationsDelegate 正是其構(gòu)造方法必須的參數(shù):

  Localizations({
    Key key,
    @required this.locale,
    @required this.delegates,                              //此處
    this.child,
  }) : assert(locale != null),
       assert(delegates != null),
       assert(delegates.any(
               (LocalizationsDelegate<dynamic> delegate)
                 => delegate is LocalizationsDelegate<WidgetsLocalizations>)
             ),
       super(key: key);

而 DemoLocalizations 的實(shí)例也是在 Localizations 中通過 DemoLocalizationsDelegate 實(shí)例化的娶视。所以在應(yīng)用中要使用 DemoLocalizations 的實(shí)例自然是需要通過 Localizations 這個(gè) Widget 來獲取的晒哄,代碼如下:

Localizations.of(context, DemoLocalizations);

of這個(gè)靜態(tài)方法就會(huì)返回 DemoLocalizations 的實(shí)例,現(xiàn)在先別管其內(nèi)部是如何實(shí)現(xiàn)的肪获。我們將這行代碼放入 DemoLocalizations 中以方便使用:

class DemoLocalizations {

  final Locale locale;

  DemoLocalizations(this.locale);

  static Map<String, Map<String, String>> _localizedValues = {
    'en': {
      'task title': 'Flutter Demo',
      'titlebar title': 'Flutter Demo Home Page',
      'click tip': 'You have pushed the button this many times:',
      'inc':'Increment'
    },
    'zh': {
      'task title': 'Flutter 示例',
      'titlebar title': 'Flutter 示例主頁面',
      'click tip': '你一共點(diǎn)擊了這么多次按鈕:',
      'inc':'增加'
    }
  };

  get taskTitle{
    return _localizedValues[locale.languageCode]['task title'];
  }

  get titleBarTitle{
    return _localizedValues[locale.languageCode]['titlebar title'];
  }

  get clickTop{
    return _localizedValues[locale.languageCode]['click tip'];
  }

  get inc{
    return _localizedValues[locale.languageCode]['inc'];
  }

  //此處
  static DemoLocalizations of(BuildContext context){
    return Localizations.of(context, DemoLocalizations);
  }
}

接下來就是真正使用 DemoLocalizations 的時(shí)候了寝凌,在代碼中將原來的字符串替換如下:

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter/foundation.dart' show SynchronousFuture;

void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: DemoLocalizations.of(context).taskTitle,                           // 此處1
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new MyHomePage(title: DemoLocalizations.of(context).titleBarTitle), // 此處2
      localizationsDelegates: [
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        DemoLocalizationsDelegate.delegate,
      ],
      supportedLocales: [
        const Locale('zh', 'CH'),
        const Locale('en', 'US'),
      ],
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    showDatePicker(context: context,
        initialDate: new DateTime.now(),
        firstDate: new DateTime.now().subtract(new Duration(days: 30)),
        lastDate: new DateTime.now().add(new Duration(days: 30))).then((v) {});
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text(widget.title),
      ),
      body: new Center(
        child: new Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            new Text(
              DemoLocalizations.of(context).clickTop,                          // 此處3
            ),
            new Text(
              '$_counter',
              style: Theme
                  .of(context)
                  .textTheme
                  .display1,
            ),
          ],
        ),
      ),
      floatingActionButton: new FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: DemoLocalizations.of(context).inc,                           // 此處4
        child: new Icon(Icons.add),
      ),
    );
  }
}

運(yùn)行!孝赫!

image

??????

當(dāng)遇到這種突如其來的問題的時(shí)候一定要淡定较木,喝口水,眺望一會(huì)遠(yuǎn)方青柄。伐债。。

接著仔細(xì)看報(bào)錯(cuò)信息:The getter 'taskTitle' was called on null.說的很明確致开,在 1 處出現(xiàn)了空指針峰锁,我們沒有像預(yù)想的一樣拿到 DemoLocalizations 對(duì)象。那問題一定出在 Localizations.of 方法內(nèi)部双戳,跟進(jìn)去看看:

  static T of<T>(BuildContext context, Type type) {
    assert(context != null);
    assert(type != null);
    final _LocalizationsScope scope =       
             context.inheritFromWidgetOfExactType(_LocalizationsScope); // 此處
    return scope?.localizationsState?.resourcesFor<T>(type);
  }

關(guān)鍵在 context.inheritFromWidgetOfExactType處虹蒋,繼續(xù)進(jìn)去:

InheritedWidget inheritFromWidgetOfExactType(Type targetType);

很簡(jiǎn)單,這是一個(gè)抽象 BuildContext 的抽象方法。此時(shí)如果再要繼續(xù)追蹤實(shí)現(xiàn)類就比較困難了魄衅,通過這個(gè)方法的注釋可以知道峭竣,它是通過 targetType 來獲取 context 最近父節(jié)點(diǎn)的對(duì)象,前提條件是 targetType 對(duì)應(yīng)的類必須是 InheriteWidget 的子類晃虫。通過查看 _LocalizationsScope發(fā)現(xiàn)其正是繼承自 InheriteWidget皆撩。那就是說沒有從 context 的父節(jié)點(diǎn)中找到 _LocalizationsScope。此時(shí)我們?cè)倏匆幌抡{(diào)用 taskTitle 的地方:

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: DemoLocalizations.of(context).taskTitle,                           // 此處
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new MyHomePage(title: DemoLocalizations.of(context).titleBarTitle),
      localizationsDelegates: [
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        DemoLocalizationsDelegate.delegate,
      ],
      supportedLocales: [
        const Locale('zh', 'CH'),
        const Locale('en', 'US'),
      ],
    );
  }
}

仔細(xì)看 taskTitle 處的 context 是從最外層的 build 方法中傳入的傲茄,而在之前說過 Localizations 這個(gè)組件是在 MaterialApp 中被嵌套的毅访,也就是說能找到 DemoLocalizations 的 context 至少需要是 MaterialApp 內(nèi)部的,而此時(shí)的 context 是無法找到 DemoLocalizations 對(duì)象的盘榨。但這樣進(jìn)入死胡同了,實(shí)現(xiàn)多語言的 DemoLocalizations 需要在 MaterialApp 內(nèi)部才能被找到蟆融,而這里的 title 用到的 context 是在 MaterialApp 外部的草巡。

難道多語言在 title 上沒法實(shí)現(xiàn)?

喝口水型酥,眺望下遠(yuǎn)方山憨。

既然如此我們不如看下這個(gè) title 的說明:

  /// A one-line description used by the device to identify the app for the user.
  ///
  /// On Android the titles appear above the task manager's app snapshots which are
  /// displayed when the user presses the "recent apps" button. Similarly, on
  /// iOS the titles appear in the App Switcher when the user double presses the
  /// home button.
  ///
  /// To provide a localized title instead, use [onGenerateTitle].
  ///
  /// This value is passed unmodified to [WidgetsApp.title].
  final String title;

請(qǐng)注意這句:To provide a localized title instead, use [onGenerateTitle].

沒想到啊,如果要對(duì) title 進(jìn)行多語言處理還需要 onGenerateTitle這個(gè)屬性弥喉。那就簡(jiǎn)單了郁竟,更改如下:

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      onGenerateTitle: (context){                                              // 此處
        return DemoLocalizations.of(context).taskTitle;
      },
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new MyHomePage(title: DemoLocalizations.of(context).titleBarTitle),
      localizationsDelegates: [
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        DemoLocalizationsDelegate.delegate,
      ],
      supportedLocales: [
        const Locale('zh', 'CH'),
        const Locale('en', 'US'),
      ],
    );
  }
}

此時(shí)運(yùn)行會(huì)發(fā)現(xiàn) taskTitle 處已經(jīng)沒問題了,但 titleBarTitle 這邊還是報(bào)錯(cuò)由境,原因一樣它的 context 使用的是 MaterialApp 外部的 context棚亩。但這里的 title 是可以被移動(dòng)到 MyHomePage 內(nèi)部初始的,所以很好修改虏杰,將 MyHomePage 構(gòu)造方法中的 title 參數(shù)移除讥蟆,直接在 AppBar 內(nèi)部賦值:

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key}) : super(key: key);

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    showDatePicker(context: context,
        initialDate: new DateTime.now(),
        firstDate: new DateTime.now().subtract(new Duration(days: 30)),
        lastDate: new DateTime.now().add(new Duration(days: 30))).then((v) {});
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text(DemoLocalizations.of(context).titleBarTitle),            // 此處
      ),
      body: new Center(
        child: new Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            new Text(
              DemoLocalizations.of(context).clickTop,
            ),
            new Text(
              '$_counter',
              style: Theme
                  .of(context)
                  .textTheme
                  .display1,
            ),
          ],
        ),
      ),
      floatingActionButton: new FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: DemoLocalizations.of(context).inc,
        child: new Icon(Icons.add),
      ),
    );
  }
}

再運(yùn)行:

image
image

完美。

三纺阔、國(guó)際化的初始化過程

上一節(jié)中簡(jiǎn)單介紹了如何在 MaterialApp 實(shí)現(xiàn)國(guó)際化瘸彤,各位可能也注意到了最終語言資源的選擇還是留給了 DemoLocalizations,而對(duì)語言資源本身是以什么形式存在沒有特別規(guī)定笛钝。在上文中我將兩國(guó)的語言放到了一個(gè) Map 中质况,自然也可以將其放在服務(wù)器上,在程序啟動(dòng)后進(jìn)行拉取玻靡,這些都是后話了结榄,在這一節(jié)中我簡(jiǎn)單剖析下源碼,看看 DemoLocalizatins 是如何在程序運(yùn)行后被初始化的啃奴。

上面已經(jīng)說過官方鼓勵(lì)我們使用 MaterialApp 作為程序入口潭陪,我們就從 MaterialApp 出發(fā),首先看 MaterialApp 的構(gòu)造方法:

  MaterialApp({ // can't be const because the asserts use methods on Map :-(
    Key key,
    this.title: '',
    this.onGenerateTitle,
    this.color,
    this.theme,
    this.home,
    this.routes: const <String, WidgetBuilder>{},
    this.initialRoute,
    this.onGenerateRoute,
    this.onUnknownRoute,
    this.locale,
    this.localizationsDelegates,
    this.localeResolutionCallback,
    this.supportedLocales: const <Locale>[const Locale('en', 'US')],
    this.navigatorObservers: const <NavigatorObserver>[],
    this.debugShowMaterialGrid: false,
    this.showPerformanceOverlay: false,
    this.checkerboardRasterCacheImages: false,
    this.checkerboardOffscreenLayers: false,
    this.showSemanticsDebugger: false,
    this.debugShowCheckedModeBanner: true
  })

上面的 localizationsDelegates是多語言的關(guān)鍵點(diǎn),由于 MaterialApp 是一個(gè) StatefulWidget依溯,所以直接看其對(duì)應(yīng)的 State 類 _MaterialAppState中的 build 方法老厌,代碼有點(diǎn)長(zhǎng):

Widget build(BuildContext context) {
    final ThemeData theme = widget.theme ?? new ThemeData.fallback();
    Widget result = new AnimatedTheme(                                // 1
      data: theme,
      isMaterialAppTheme: true,
      child: new WidgetsApp(                                          //2
        key: new GlobalObjectKey(this),
        title: widget.title,
        onGenerateTitle: widget.onGenerateTitle,
        textStyle: _errorTextStyle,
        // blue is the primary color of the default theme
        color: widget.color ?? theme?.primaryColor ?? Colors.blue,
        navigatorObservers:
            new List<NavigatorObserver>.from(widget.navigatorObservers)
              ..add(_heroController),
        initialRoute: widget.initialRoute,
        onGenerateRoute: _onGenerateRoute,
        onUnknownRoute: _onUnknownRoute,
        locale: widget.locale,
        localizationsDelegates: _localizationsDelegates,                  //3
        localeResolutionCallback: widget.localeResolutionCallback,
        supportedLocales: widget.supportedLocales,
        showPerformanceOverlay: widget.showPerformanceOverlay,
        checkerboardRasterCacheImages: widget.checkerboardRasterCacheImages,
        checkerboardOffscreenLayers: widget.checkerboardOffscreenLayers,
        showSemanticsDebugger: widget.showSemanticsDebugger,
        debugShowCheckedModeBanner: widget.debugShowCheckedModeBanner,
        inspectorSelectButtonBuilder: (BuildContext context, VoidCallback onPressed) {
          return new FloatingActionButton(
            child: const Icon(Icons.search),
            onPressed: onPressed,
            mini: true,
          );
        },
      )
    );

    assert(() {
      if (widget.debugShowMaterialGrid) {    //此處如果有配置,則會(huì)顯示網(wǎng)格
        result = new GridPaper(
          color: const Color(0xE0F9BBE0),
          interval: 8.0,
          divisions: 2,
          subdivisions: 1,
          child: result,
        );
      }
      return true;
    }());

    return new ScrollConfiguration(                                // 4
      behavior: new _MaterialScrollBehavior(),
      child: result,
    );
  }

首先在 3 處可以看到 _localizationsDelegates 被賦值給了 WidgetsApp 的 localizationsDelegates 參數(shù)黎炉。在看 1枝秤、2、4 處分別又在原有的 Widget 上做了包裹慷嗜,此時(shí)的 widget 樹層次如下圖:

[圖片上傳失敗...(image-74770b-1525245587456)]

接著進(jìn)入 WidgetApp 淀弹,它也是個(gè) StatefulWidget,直接看它的 State 類 _WidgetsAppState的 build 方法:

 Widget build(BuildContext context) {
    Widget result = new Navigator(                                    // 1
      key: _navigator,
      initialRoute: widget.initialRoute ?? ui.window.defaultRouteName,
      onGenerateRoute: widget.onGenerateRoute,
      onUnknownRoute: widget.onUnknownRoute,
      observers: widget.navigatorObservers,
    );

    if (widget.textStyle != null) {
      result = new DefaultTextStyle(                                    //2
        style: widget.textStyle,
        child: result,
      );
    }

    ... //此處省略調(diào)試相關(guān)代碼

    return new MediaQuery(                                              //3
      data: new MediaQueryData.fromWindow(ui.window),
      child: new Localizations(                                         //4
        locale: widget.locale ?? _locale,
        delegates: _localizationsDelegates.toList(),
        // This Builder exists to provide a context below the Localizations widget.
        // The onGenerateCallback() can refer to Localizations via its context
        // parameter.
        child: new Builder(                                             //5
          builder: (BuildContext context) {
            String title = widget.title;
            if (widget.onGenerateTitle != null) {
              title = widget.onGenerateTitle(context);
              assert(title != null, 'onGenerateTitle must return a non-null String');
            }
            return new Title(                                            //6
              title: title,
              color: widget.color,
              child: result,
            );
          },
        ),
      ),
    );
  }

在 4 處終于見到了我們熟悉的身影 Localizatins庆械。_localizationsDelegates 也是被傳遞進(jìn)了 Localizations薇溃。此時(shí)的 widget 樹層次如下:

[圖片上傳失敗...(image-901681-1525245587456)]

層次如此之多,但我們關(guān)心只是其中的 Localizations缭乘,所以拋開其他不看沐序,進(jìn)入 Localizations 看看。

不出意外 Localizations 也是一個(gè) StatefulWidget堕绩,此時(shí)我們不需要關(guān)心它的 build 方法策幼,而是應(yīng)該關(guān)注其內(nèi)部的 initState 方法,如果有數(shù)據(jù)需要初始化奴紧,不出意外就是在這里進(jìn)行特姐。

initState 方法很短:

  @override
  void initState() {
    super.initState();
    load(widget.locale);
  }

繼續(xù)進(jìn)入 load 方法:

  void load(Locale locale) {
    final Iterable<LocalizationsDelegate<dynamic>> delegates = widget.delegates; // 1
    if (delegates == null || delegates.isEmpty) {
      _locale = locale;
      return;
    }

    Map<Type, dynamic> typeToResources;
    final Future<Map<Type, dynamic>> typeToResourcesFuture = _loadAll(locale, delegates) //2
      .then((Map<Type, dynamic> value) {
        return typeToResources = value;
      });
    
    ...
  
  }

1 處的 delegates 即一開始從 MaterialApp 傳入的 delegate 數(shù)組,這里轉(zhuǎn)成立可迭代對(duì)象黍氮。接著看 2 處的 _loadAll 方法返回的 typeToResourcesFuture 唐含,其中的值類型為 Map<Type, dynamic>,這里可以推敲出來里邊的 Type 對(duì)應(yīng)的就是不同的 Localizations滤钱,而 dynamic 則是其實(shí)例觉壶。帶著這樣的想法看 _loadAll 方法:

Future<Map<Type, dynamic>> _loadAll(Locale locale, Iterable<LocalizationsDelegate<dynamic>> allDelegates) {
  final Map<Type, dynamic> output = <Type, dynamic>{};
  List<_Pending> pendingList;

  // Only load the first delegate for each delegate type that supports
  // locale.languageCode.
  final Set<Type> types = new Set<Type>();
  final List<LocalizationsDelegate<dynamic>> delegates = <LocalizationsDelegate<dynamic>>[];
  for (LocalizationsDelegate<dynamic> delegate in allDelegates) {
    if (!types.contains(delegate.type) && delegate.isSupported(locale)) {
      types.add(delegate.type);
      delegates.add(delegate);          
    }
  }

  for (LocalizationsDelegate<dynamic> delegate in delegates) {
    final Future<dynamic> inputValue = delegate.load(locale);    // 1
    dynamic completedValue;
    final Future<dynamic> futureValue = inputValue.then<dynamic>((dynamic value) {
      return completedValue = value;                             // 2
    });
    if (completedValue != null) { // inputValue was a SynchronousFuture
      final Type type = delegate.type;
      assert(!output.containsKey(type));
      output[type] = completedValue;
    } else {
      pendingList ??= <_Pending>[];
      pendingList.add(new _Pending(delegate, futureValue));
    }
  }

  // All of the delegate.load() values were synchronous futures, we're done.
  if (pendingList == null)
    return new SynchronousFuture<Map<Type, dynamic>>(output);

  // Some of delegate.load() values were asynchronous futures. Wait for them.
  return Future.wait<dynamic>(pendingList.map((_Pending p) => p.futureValue))
    .then<Map<Type, dynamic>>((List<dynamic> values) {
      assert(values.length == pendingList.length);
      for (int i = 0; i < values.length; i += 1) {
        final Type type = pendingList[i].delegate.type;
        assert(!output.containsKey(type));
        output[type] = values[i];
      }
      return output;
    });
}

看 1 處,調(diào)用到了 deletegate 的 load 方法件缸,返回一個(gè) Future 铜靶,這里為什么不直接返回DemoLocalizations 的實(shí)例而要返回 Future,這個(gè)在前面也提到了如果你的資源是放在服務(wù)器上的他炊,那么這就是一個(gè)耗時(shí)操作争剿,所以在此處用了 Future。

  @override
  Future<DemoLocalizations> load(Locale locale) {
    return new SynchronousFuture<DemoLocalizations>(new DemoLocalizations(locale));
  }

由于這里返回的是 SynchronousFuture 痊末,所以在 2 處的代碼會(huì)被順序執(zhí)行蚕苇,此時(shí) completedValue 就是 DemoLocalizations 的實(shí)例對(duì)象了。然后 completedValue 被放入了 output 接著就返回出去了凿叠,最后賦值給了 _LocalizationsState 的 _typeToResources 變量涩笤。

到目前為止整個(gè)多語言的加載就完成了嚼吞,剩下的就是等著被使用。下面看一下使用的方式:

DemoLocalizations.of(context).taskTitle

簡(jiǎn)單粗暴蹬碧,根本看不出來是怎么拿到 DemoLocalizations 對(duì)象的舱禽。不多說,看代碼:

return Localizations.of(context, DemoLocalizations);

內(nèi)部調(diào)用的是 Localizations 的 of 靜態(tài)方法恩沽,接著看:

static T of<T>(BuildContext context, Type type) {
  assert(context != null);
  assert(type != null);
  final _LocalizationsScope scope = context.inheritFromWidgetOfExactType(_LocalizationsScope);
  return scope?.localizationsState?.resourcesFor<T>(type);
}

前面已經(jīng)講解過 context.inheritFromWidgetOfExactType 的作用誊稚,這里的 scope 就是最靠近 context 節(jié)點(diǎn)的 _LocalizationsScope 類型的節(jié)點(diǎn)。但我們看了上面的 widget 樹的層次圖罗心,并沒有看到 _LocalizationsScope 這個(gè) widget,它是在什么時(shí)候被添加進(jìn)去的呢里伯?

回到 _LocalizationsState 的 build 方法:

  @override
  Widget build(BuildContext context) {
    if (_locale == null)
      return new Container();
    return new _LocalizationsScope(
      key: _localizedResourcesScopeKey,
      locale: _locale,
      localizationsState: this,
      typeToResources: _typeToResources,
      child: new Directionality(
        textDirection: _textDirection,
        child: widget.child,
      ),
    );
  }

真想(●—●)。在 Localizations 的內(nèi)部渤闷,它將它原本的子節(jié)點(diǎn)外又嵌套了 Directionality疾瓮、_LocalizationsScope、Container 這三層飒箭。其中 _LocalizationsScope 就是我們想找的爷贫。

接著看:

  return scope?.localizationsState?.resourcesFor<T>(type);

此處調(diào)用了 _LocalizationsState 的 resourcesFor 方法:

  T resourcesFor<T>(Type type) {
    assert(type != null);
    final T resources = _typeToResources[type];
    return resources;
  }

到這差不多就結(jié)束了,這里根據(jù) type 從 _typeToResources 中取出了 DemoLocalizations 的實(shí)例补憾。
最后再把完整的 widget 樹的層次展示一下:

[圖片上傳失敗...(image-d220cd-1525245587456)]

四、簡(jiǎn)單的 App 內(nèi)語言切換

下面我見到介紹一下如何在不切換手機(jī)系統(tǒng)的語言的情況下來切換 Flutter 應(yīng)用內(nèi)的語言卷员。主要用到的是 Localizations 的 override 方法盈匾。具體不多介紹,看下面我自定義的 StatefulWidget 類 FreeLocalizations 和它的 State 類 _FreeLocalizations:

class FreeLocalizations extends StatefulWidget{

  final Widget child;

  FreeLocalizations({Key key,this.child}):super(key:key);

  @override
  State<FreeLocalizations> createState() {
    return new _FreeLocalizations();
  }
}

class _FreeLocalizations extends State<FreeLocalizations>{

  Locale _locale = const Locale('zh','CH');

  changeLocale(Locale locale){
    setState((){
      _locale = locale;
    });
  }
  
  @override
  Widget build(BuildContext context) {
    return new Localizations.override(
      context: context,
      locale: _locale,
      child: widget.child,
    );
  }
}

上面代碼的意思比較清晰毕骡,就是在調(diào)用 changeLocale 方法的時(shí)候修改其內(nèi)部 widget 的語言削饵。
下面來如何使用:

void main() {
  runApp(new MyApp());
}

GlobalKey<_FreeLocalizations> freeLocalizationStateKey = new GlobalKey<_FreeLocalizations>();   // 1
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      onGenerateTitle: (context){
        return DemoLocalizations.of(context).taskTitle;
      },
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new Builder(builder: (context){
        return new FreeLocalizations(
          key: freeLocalizationStateKey,
          child: new MyHomePage(),
        );
      }),
      localizationsDelegates: [
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        DemoLocalizationsDelegate.delegate,
      ],
      supportedLocales: [
        const Locale('zh', 'CH'),
        const Locale('en', 'US'),
      ],
    );
  }
}

注意想要在 FreeLocalizations 外部去調(diào)用其方法需要使用到 GlobalKey 的幫助,用法見 1 處未巫。讓后我們將 MyHomePage 放入 FreeLocalizations 內(nèi)部窿撬。

接著在點(diǎn)擊按鈕的時(shí)候調(diào)用如下方法:

  void changeLocale(){
    if(flag){
      freeLocalizationStateKey.currentState.changeLocale(const Locale('zh',"CH"));
    }else{
      freeLocalizationStateKey.currentState.changeLocale(const Locale('en',"US"));
    }
    flag = !flag;
  }

效果如下:

image

這一小節(jié)我講的比較簡(jiǎn)單,但如果你看明白了二叙凡、三兩節(jié)劈伴,那弄明白這里多語言是怎么切換的應(yīng)該是比較容易的。

五握爷、總結(jié)

思維導(dǎo)圖地址:https://my.mindnode.com/7u6RudyGs5bqzX1WrxY5XtZZqUDBzqvL2NioVbrr
文章中出現(xiàn)的代碼的地址:https://github.com/flutter-dev/internationalizing

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末跛璧,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子新啼,更是在濱河造成了極大的恐慌追城,老刑警劉巖,帶你破解...
    沈念sama閱讀 216,402評(píng)論 6 499
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件燥撞,死亡現(xiàn)場(chǎng)離奇詭異座柱,居然都是意外死亡迷帜,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,377評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門色洞,熙熙樓的掌柜王于貴愁眉苦臉地迎上來戏锹,“玉大人,你說我怎么就攤上這事锋玲【坝茫” “怎么了?”我有些...
    開封第一講書人閱讀 162,483評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵惭蹂,是天一觀的道長(zhǎng)伞插。 經(jīng)常有香客問我,道長(zhǎng)盾碗,這世上最難降的妖魔是什么媚污? 我笑而不...
    開封第一講書人閱讀 58,165評(píng)論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮廷雅,結(jié)果婚禮上耗美,老公的妹妹穿的比我還像新娘。我一直安慰自己航缀,他們只是感情好商架,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,176評(píng)論 6 388
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著芥玉,像睡著了一般蛇摸。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上灿巧,一...
    開封第一講書人閱讀 51,146評(píng)論 1 297
  • 那天赶袄,我揣著相機(jī)與錄音,去河邊找鬼抠藕。 笑死饿肺,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的盾似。 我是一名探鬼主播敬辣,決...
    沈念sama閱讀 40,032評(píng)論 3 417
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼颜说!你這毒婦竟也來了购岗?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,896評(píng)論 0 274
  • 序言:老撾萬榮一對(duì)情侶失蹤门粪,失蹤者是張志新(化名)和其女友劉穎喊积,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體玄妈,經(jīng)...
    沈念sama閱讀 45,311評(píng)論 1 310
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡乾吻,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,536評(píng)論 2 332
  • 正文 我和宋清朗相戀三年髓梅,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片绎签。...
    茶點(diǎn)故事閱讀 39,696評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡枯饿,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出诡必,到底是詐尸還是另有隱情奢方,我是刑警寧澤,帶...
    沈念sama閱讀 35,413評(píng)論 5 343
  • 正文 年R本政府宣布爸舒,位于F島的核電站蟋字,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏扭勉。R本人自食惡果不足惜鹊奖,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,008評(píng)論 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望涂炎。 院中可真熱鬧忠聚,春花似錦、人聲如沸唱捣。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,659評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽震缭。三九已至垫竞,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間蛀序,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,815評(píng)論 1 269
  • 我被黑心中介騙來泰國(guó)打工活烙, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留徐裸,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 47,698評(píng)論 2 368
  • 正文 我出身青樓啸盏,卻偏偏與公主長(zhǎng)得像重贺,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子回懦,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,592評(píng)論 2 353

推薦閱讀更多精彩內(nèi)容

  • ¥開啟¥ 【iAPP實(shí)現(xiàn)進(jìn)入界面執(zhí)行逐一顯】 〖2017-08-25 15:22:14〗 《//首先開一個(gè)線程气笙,因...
    小菜c閱讀 6,401評(píng)論 0 17
  • 譯者丨覃云 Flutter 是什么潜圃? Flutter 移動(dòng)應(yīng)用程序 SDK 是為開發(fā)人員提供一種創(chuàng)建快捷、美觀的應(yīng)...
    言射手閱讀 7,815評(píng)論 1 14
  • 北書房閱讀 371評(píng)論 0 11
  • 這是一篇宣言舟茶,我稱它為日更宣言谭期。 內(nèi)容大概是這樣的: 1.連續(xù)21天公眾號(hào)日更堵第。 2.每天內(nèi)容1000字以上。 3...
    我以前是學(xué)渣閱讀 146評(píng)論 0 0
  • 在我們開發(fā)中,經(jīng)常會(huì)遇到一些需要?jiǎng)赢嬏匦У恼故?下面來總結(jié)一些開發(fā)中常見的動(dòng)畫實(shí)現(xiàn)方式 第一,幀動(dòng)畫,通過大量的U...
    CoderSC閱讀 327評(píng)論 0 1