Flutter-Flutter1.22最新的多國語支持配置和使用

Flutter1.22最新的多國語支持配置和使用

Flutter1.22現(xiàn)已發(fā)布

? 最新版本中脖祈,隨之發(fā)布了很多新的特性以及修復(fù)了一些bug,現(xiàn)在我們說說其中的新的多國語插件刷晋。個(gè)人感覺新多國語操作,多了一些模板性的東西眼虱,但是也方便了很多東西。

? 話不多說捏悬,現(xiàn)在我們進(jìn)入正題撞蚕,如果使用新插件呢?

配置項(xiàng)目的yaml文件

dependencies:
  flutter:
    sdk: flutter
  flutter_localizations: #配置多國語支持
    sdk: flutter
  intl: 0.16.1   #多國語插件
  
  
flutter:

  # The following line ensures that the Material Icons font is
  # included with your application, so that you can use the icons in
  # the material Icons class.
  uses-material-design: true

  generate: true  #新增配置邮破,自動(dòng)多國語代碼生成

?

項(xiàng)目新增配置l10n.yaml

arb-dir: lib/l10n  #指定arb多國語文件目錄
template-arb-file: app_zh.arb #指定arb多國語文件
output-localization-file: app_localizations.dart  #指定多國語配置生成的代碼文件,代碼中自動(dòng)生成類文件AppLocalizations.dart

l10n.yaml 文件可配置的屬性有:

屬性 描述
arb-dir The directory where the template and translated arb files are located. (defaults to "lib/l10n")
output-dir The directory where the generated localization classes will be written. This option is only relevant if you want to generate the localizations code somewhere else in the Flutter project. You will also need to set the synthetic-package flag to false.<br />The app must import the file specified in the 'output-localization-file' option from this directory. If unspecified, this defaults to the same directory as the input directory specified in 'arb-dir'.
template-arb-file The template arb file that will be used as the basis for generating the Dart localization and messages files. (defaults to "app_en.arb")
output-localization-file The filename for the output localization and localizations delegate classes. (defaults to "app_localizations.dart")
untranslated-messages-file The location of a file that describes the localization messages have not been translated yet. Using this option will create a JSON file at the target location, in the following format:
"locale": ["message_1", "message_2" ... "message_n"]
If this option is not specified, a summary of the messages that have not been translated will be printed on the command line.
output-class The Dart class name to use for the output localization and localizations delegate classes. (defaults to "AppLocalizations")
preferred-supported-locales The list of preferred supported locales for the application. By default, the tool will generate the supported locales list in alphabetical order. Use this flag if you would like to default to a different locale.
For example, pass in [ en_US ] if you would like your app to default to American English if a device supports it.
synthetic-package Determines whether or not the generated output files will be generated as a synthetic package or at a specified directory in the Flutter project.
This flag is set to true by default.<br />When synthetic-package is set to false, it will generate the localizations files in the directory specified by arb-dir by default.<br />If output-dir is specified, files will be generated there.
header The header to prepend to the generated Dart localizations files. This option takes in a string.
For example, pass in "http:/// All localized files." if you would like this string prepended to the generated Dart file.
Alternatively, see the header-file option to pass in a text file for longer headers.
header-file The header to prepend to the generated Dart localizations files. The value of this option is the name of the file that contains the header text which will be inserted at the top of each generated Dart file.
Alternatively, see the header option to pass in a string for a simpler header.
This file should be placed in the directory specified in 'arb-dir'.
[no-]use-deferred-loading Whether to generate the Dart localization file with locales imported as deferred, allowing for lazy loading of each locale in Flutter web.
This can reduce a web app’s initial startup time by decreasing the size of the JavaScript bundle. When this flag is set to true, the messages for a particular locale are only downloaded and loaded by the Flutter app as they are needed. For projects with a lot of different locales and many localization strings, it can be a performance improvement to have deferred loading. For projects with a small number of locales, the difference is negligible, and might slow down the start up compared to bundling the localizations with the rest of the application.
Note that this flag does not affect other platforms such as mobile or desktop.

項(xiàng)目中使用多國語化

? 新建arb文件摧莽,項(xiàng)目下lib文件目錄下新建l10n文件夾,然后新建app_zh.arb多國語文件

? app_zh.arb文件中配置如下:

{
    "@@locale": "zh", //標(biāo)識(shí)語言為中文
    "homePageTitle": "首頁", //標(biāo)識(shí)名
    "@homePageTitle": { //標(biāo)識(shí)對應(yīng)的一些屬性描述
        "description": "主頁標(biāo)題"
    },
    "helloWorld": "世界你好啊蚁袭!{userName}", //標(biāo)識(shí)名及參數(shù)數(shù)據(jù)
    "@helloWorld": { //標(biāo)識(shí)對應(yīng)的一些屬性描述
        "description": "The conventional newborn programmer greeting",
        "placeholders": { //占位符描述
            "userName": {
                "type": "String", //占位符類型
                "example": "小明" 
            }
        }
    }
}

然后重新Rebuild項(xiàng)目石咬,項(xiàng)目會(huì)自動(dòng)生成app_localizations.dart文件,使用方法 AppLocalizations.of(context).標(biāo)識(shí)符 獲得該標(biāo)識(shí)對應(yīng)的字符串删性。

  1. main.dart 文件

    import 'package:flutter_gen/gen_l10n/app_localizations.dart'; // 添加改行引用
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) => MaterialApp(
          onGenerateTitle: (context) =>
              AppLocalizations.of(context).helloWorld("Hello 1"), //引用多國語標(biāo)識(shí)
          theme: ThemeData(
              primarySwatch: Colors.blue,
              visualDensity: VisualDensity.adaptivePlatformDensity),
          localizationsDelegates: AppLocalizations.localizationsDelegates,
          supportedLocales: AppLocalizations.supportedLocales,
          home: HomePage());
    }
    
  1. home_page.dart 文件

    import 'package:flutter_gen/gen_l10n/app_localizations.dart'; // 添加改行引用
      
    class HomePage extends StatefulWidget {
      HomePage({Key key}) : super(key: key);
    
      @override
      _HomePageState createState() => _HomePageState();
    }
    
    class _HomePageState extends State<HomePage> {
      @override
      Widget build(BuildContext context) => Scaffold(
          appBar: AppBar(
              centerTitle: true,
              title: Text(AppLocalizations.of(context).homePageTitle)), //引用多國語標(biāo)識(shí)
          body: Container(
              alignment: Alignment.center,
              child: Column(
                  mainAxisAlignment: MainAxisAlignment.start,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Text(AppLocalizations.of(context).helloWorld("hello 2"))
                  ])),
          bottomNavigationBar: BottomNavigationBar(items: [
            BottomNavigationBarItem(icon: Icon(Icons.home), label: "首頁"),
            BottomNavigationBarItem(icon: Icon(Icons.person), label: "我的"),
            BottomNavigationBarItem(icon: Icon(Icons.person), label: "我的"),
          ]));
    }
    
    

其他相關(guān)多國語化參數(shù)描述蹬挺,如下:

  1. 字符串

    {
      "hello" : "Hello{userName}", 
        "@hello" : {
        "description":"Amessagewithasingleparameter",
      "placeholders": {
        "userName": {
        "type":"String", 
        "example": "Bob"
            }
      }
    }
    

    調(diào)用方式:AppLocalizations.of(context).hello("Jacket Chen")

  2. 多個(gè)參數(shù)

    {
      "greeting":"{hello} {world}",
        "@greeting": {
            "description": "Amessagewithatwoparameters",
        "placeholders": {
                    "hello": {}, //{}中占位符屬性描述
                    "world": {} //同上
        }
    }
    

    調(diào)用方式:AppLocalizations.of(context).greeting('Hello', 'World')

    1. 數(shù)字以及貨幣

    NumberFormat.compactLong("en_US").format(1200000) 該調(diào)用結(jié)果為:1.2million

    你可以使用類型為int或者double的占位符來表達(dá)同樣的結(jié)果:

    {
      "numberOfDataPoints": "Number of data points: {value}",
        "@numberOfDataPoints": {
        "description": "Amessagewithaformattedintparameter",
        "placeholders": {
                "value": {
                    "type":"int", 
            "format": "compactLong"
                } 
        }
    }
    

    調(diào)用方式:AppLocalizations.of(context).numberOfDataPoints(1200000)

    format對應(yīng)的取值巴帮,如下:

    format的取值 numberOfDataPoints(1200000) 對應(yīng)的輸出結(jié)果
    compact 1.2M
    compactCurrency* $1.2M
    compactSimpleCurrency* $1.2M
    compactLong 1.2 millions
    currency* USD1,200,000.00
    decimalPattern 1,200,000
    decimalPercentPattern* 120,000,000%
    percentPattern 120,000,000%
    scientificPattern 1E6
    simpleCurrency* $1,200,000.00

    :帶星號(hào)的格式對應(yīng)的取值有可選參數(shù)類型虐秋,如:optionalParameters*,他們的構(gòu)造函數(shù)有可選參數(shù)雪猪。

    配置方式如下:

    {
      "numberOfDataPoints": "Number of data points: {value}",
      "@numberOfDataPoints": {
                "description": "Amessagewithaformattedintparameter",
            "placeholders" : {
                        "value": {
                            "type": "int",
                            "format": "compactCurrency",
                            "optionalParameters": {
                    "decimalDigits" : 2
                            }
                }
       }
    }
    

    當(dāng)配置以上內(nèi)容以后起愈,numberOfDataPoints()的輸出結(jié)果將會(huì)是:USD1.20M

    1. 日期
    {
      "helloWorldOn": "Hello World on {date}",
      "@helloWorldOn": {
                "description": "Amessagewithadateparameter", 
            "placeholders": {
                        "date": { 
                "type": "DateTime", 
                "format": "yMd" //日期輸出格式
              }
          }
      }
    }
    

    在應(yīng)用中抬虽,如果語言是英語(美國),將輸出表達(dá)式 7/10/1996 ; 如果語言是俄語阐污,將輸出表達(dá)式 10.07.1996
    調(diào)用方式:AppLocalizations.of(context).helloWorldOn(DateTime.utc(1996,7,10))

    1. 復(fù)數(shù)

    一般情況下笛辟,數(shù)字在不同數(shù)量下有不同的展示效果序苏,在這里,要求數(shù)據(jù)類型必須是整型忱详,而且要求數(shù)據(jù)必須大于等于0。在新的多國語化插件配置中监透,有以下多種可選配置。

    要表達(dá)的結(jié)果 表達(dá)式
    zero =0{no wombats}
    one =1{one wombat}
    two =2{two wombats}
    few few{the {count} wombats}
    3-10, fractions many{{count} wombats}
    other other{{count} wombats}

    :表達(dá)式開始必須聲明變量以及使用plural*標(biāo)識(shí)該表達(dá)式為復(fù)數(shù)表達(dá)式院刁,如下案例:

    "nWombats": "{count,plural, =0{no wombats} other{{count} wombats}}",?
    "@nWombats": {
        "description" : "Apluralmessage",
      "placeholders" : {
                "count": { 
            "type" : "int",
                }
      }
    }
    

    *:如果表達(dá)式中還會(huì)有其他表達(dá)式的值粪狼,則可以如下編寫:

    "nThings": "{count,plural, =0{no {thing}s} other{{count} {thing}s}}",
    "@nThings": {
            "description" : "Apluralmessagewithanadditionalparameter",
        "placeholders" : {
                    "count" : { 
              "type" :"int"
                    },
            "thing" : {
              "example" :"wombat"
                    }
            }
    }
    

    nThings(0, “wombat”) 和 nThings(5, “wombat”) 將返回與之前一樣的字符串。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末阅虫,一起剝皮案震驚了整個(gè)濱河市不跟,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌购城,老刑警劉巖虐译,帶你破解...
    沈念sama閱讀 211,265評論 6 490
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異侮攀,居然都是意外死亡厢拭,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,078評論 2 385
  • 文/潘曉璐 我一進(jìn)店門畦贸,熙熙樓的掌柜王于貴愁眉苦臉地迎上來楞捂,“玉大人,你說我怎么就攤上這事寨闹。” “怎么了涵但?”我有些...
    開封第一講書人閱讀 156,852評論 0 347
  • 文/不壞的土叔 我叫張陵,是天一觀的道長瞳脓。 經(jīng)常有香客問我澈侠,道長,這世上最難降的妖魔是什么哨啃? 我笑而不...
    開封第一講書人閱讀 56,408評論 1 283
  • 正文 為了忘掉前任拳球,我火速辦了婚禮,結(jié)果婚禮上祝峻,老公的妹妹穿的比我還像新娘。我一直安慰自己酬姆,他們只是感情好奥溺,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,445評論 5 384
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著相满,像睡著了一般壶唤。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上闸盔,一...
    開封第一講書人閱讀 49,772評論 1 290
  • 那天琳省,我揣著相機(jī)與錄音,去河邊找鬼击费。 笑死桦他,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播垃瞧,決...
    沈念sama閱讀 38,921評論 3 406
  • 文/蒼蘭香墨 我猛地睜開眼坪郭,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了嗦锐?” 一聲冷哼從身側(cè)響起沪曙,我...
    開封第一講書人閱讀 37,688評論 0 266
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎碳默,沒想到半個(gè)月后育灸,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 44,130評論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡儿子,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,467評論 2 325
  • 正文 我和宋清朗相戀三年砸喻,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片割岛。...
    茶點(diǎn)故事閱讀 38,617評論 1 340
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡癣漆,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出惠爽,到底是詐尸還是另有隱情,我是刑警寧澤租副,帶...
    沈念sama閱讀 34,276評論 4 329
  • 正文 年R本政府宣布较性,位于F島的核電站结胀,受9級特大地震影響责循,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜沼死,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,882評論 3 312
  • 文/蒙蒙 一意蛀、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧县钥,春花似錦、人聲如沸省有。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,740評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽匾效。三九已至,卻和暖如春野宜,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背匈子。 一陣腳步聲響...
    開封第一講書人閱讀 31,967評論 1 265
  • 我被黑心中介騙來泰國打工闯袒, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人原茅。 一個(gè)月前我還...
    沈念sama閱讀 46,315評論 2 360
  • 正文 我出身青樓堕仔,卻偏偏與公主長得像晌区,于是被迫代替她去往敵國和親通贞。 傳聞我的和親對象是個(gè)殘疾皇子恼五,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,486評論 2 348