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
標記,設置參數
docId
→ Google Sheet URL 上擷取的 IDversion
→ 代表多語系版本,每次更新 Google Sheet 後都可以更新此數字,接著重新生成檔案outDir
→ 生成檔案的所在目錄outName
→ 生成檔案的名稱
- 記得使用 part 在上方給予生成檔案的位置
新增資料夾,存放語言翻譯檔案,通常在 assets/
裡面
執行 build_runner
生成檔案
flutter pub run build_runner build --delete-conflicting-outputs
設置 APP 載入多語系
- 在起始點 APP 外層包上
EasyLocalization
- 設置
path
,CSV翻譯檔案 - 設置
supportedLocales
,支援地區語言,通常就存取檔案裡的 supportedLocales - 設置
assetLoader
,設置載入讀取器,通常 Google Sheet 為 csv 格式,使用 CsvAssetLoader - 可以設置
fallbackLocale
,預設語言,當 supportedLocales 有語言找不到時,會使用預設語言 - 可以設置
startLocale
,指定語言地區,代替手機裡的系統語言
7. 為 MaterialApp 設置地區資訊
localizationsDelegates: context.localizationDelegates,
supportedLocales: context.supportedLocales,
locale: context.locale,
初始化
開啟 APP 前進行多語系套件初始化
實際開發
原本官方套件在使用多語系字串時都需要在後方額外加上 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 多語系翻譯就完成了,繼續加油吧!
其他文章
- Flutter CICD 使用 Gitlab Runner 和 App Center 實作 part.1
- 使用 CodeMagic 和 Firebase 實現 Flutter CICD
- 輕鬆完成Flutter開發環境,最新版!
- 實作Flutter多變有趣的滾動效果CustomScrollView!
- 如何在Flutter使用 Makefile 節省你的時間?
- Easily understand StatefulWidget LifeCycle of Flutter
- “freezed” makes model class strong and easily
- 提高Flutter性能的小技巧!(一)
- 提高Flutter性能的小技巧!(二)
- 提高Flutter性能的小技巧!(三)
- What are Async and Isolates in Flutter?
- LoadBalancer is optimization for Isolates in Flutter
- Riverpod 輕鬆學,原來這麼好用!
- Riverpod 輕鬆學(二),一些進階用法!
關於我
- GitHub: chyiiiiiiiiiiii
- Instagram: flutterluvr.yii
- Linkedin: yiichenhi
- Youtube: Yii
- Youtube: 一起饅頭(美食頻道)
- Email: ab20803@gmail.com
贊助
謝謝你花費時間看完,非常感謝!
如果覺得文章不錯的話可以贊助,讓我有更多動力和熱情分享學習紀錄和生活!請我喝一杯咖啡吧~
最後
希望有幫助到你/妳,歡迎追蹤我,方便瀏覽最新的文章~