Flutter 輕鬆實作 i18n,使用 easy_localization_generator 就對了

Yii Chen
8 min readDec 1, 2022

這套 i18n 非常利於開發 UI 時使用

本文教你使用 easy_localization 套件實作 Flutter i18n,其中 easy_localization_generator 套件負責取得 Google sheet 並生成字串檔與翻譯檔,接著透過 easy_localization_loader 套件存取翻譯檔,最後就能依據設置地區顯示對應語言字串。

跟著我的步驟,輕鬆幫你的專案加上 i18n 吧!

Packages

Installaction

dependencies:
flutter:
sdk: flutter

easy_localization: <last_version>
easy_localization_loader: <last_version>
easy_localization_generator: <last_version>

建立 Google Sheet 試算表

新增想要翻譯的地區,並設置字串

範例

將共享打開,並給予檢視者權限就好

取得試算表ID,Doc ID,存取時需要使用

https://docs.google.com/spreadsheets/d/<DOC-ID>/edit#gid=0

生成語言檔案

  • 新增 i18n 存取檔案,負責讀取字串。我將它放在 lib/localization/,檔案名稱為 i18n
  • 添加 @SheetLocalization 標記,設置參數
  1. docId → Google Sheet URL 上擷取的 ID
  2. version → 代表多語系版本,每次更新 Google Sheet 後都可以更新此數字,接著重新生成檔案
  3. outDir → 生成檔案的所在目錄
  4. outName → 生成檔案的名稱
  • 記得使用 part 在上方給予生成檔案的位置

新增資料夾,存放語言翻譯檔案,通常在 assets/ 裡面

create a folder

執行 build_runner 生成檔案

flutter pub run build_runner build --delete-conflicting-outputs
new i18n.g.dart and langs.csv files
generated CSV file from sheet
generated I18n class that includes operations of translation

設置 APP 載入多語系

  1. 在起始點 APP 外層包上 EasyLocalization
  2. 設置 path,CSV翻譯檔案
  3. 設置 supportedLocales,支援地區語言,通常就存取檔案裡的 supportedLocales
  4. 設置 assetLoader,設置載入讀取器,通常 Google Sheet 為 csv 格式,使用 CsvAssetLoader
  5. 可以設置 fallbackLocale,預設語言,當 supportedLocales 有語言找不到時,會使用預設語言
  6. 可以設置 startLocale,指定語言地區,代替手機裡的系統語言
main.dart

7. 為 MaterialApp 設置地區資訊

localizationsDelegates: context.localizationDelegates,
supportedLocales: context.supportedLocales,
locale: context.locale,

初始化

開啟 APP 前進行多語系套件初始化

initialize before app runs in main()

實際開發

原本官方套件在使用多語系字串時都需要在後方額外加上 tr(),覺得有點多餘,當然如果字串裡面要帶參數更新文字或是其他操作當然不可避免。而這邊我優化了 easy_localization_generator 套件,目前版本已 Merged 到官方套件,大大改善使用方式,可生成自帶命名參數的函式,讓開發者不用再想需要設置什麼 Key,直接輕鬆帶入 Value 即可,另外 plural 使用方式也有調整。

1. 一般文字

I18n.title

2. 指定參數

Text(
I18n.msg(
name: 'Jack',
type: 'Hot',
),
),

3. 複數單位

Text(I18n.amount(counter))
Text(
I18n.clicked(
counter,
count: counter.toString(),
),
),

範例 DEMO

到這邊 i18n 多語系翻譯就完成了,繼續加油吧!

--

--

Yii Chen

Flutter Lover || Organizer FlutterTaipei || Writer, Speaker || wanna make Flutter strong in Taiwan. https://linktr.ee/yiichenhi