fis_i18n.dart 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. import 'package:fis_i18n/i18n.dart';
  2. import 'package:fis_i18n/types.dart';
  3. import 'package:flutter/cupertino.dart';
  4. import 'package:flutter/services.dart';
  5. import 'package:flyinsonolite/localization/fis_keybook.dart';
  6. typedef FTrKeybookBuilder = Future<FISTrKeybook> Function();
  7. typedef FI18nLocaleUpdater = void Function(Locale locale);
  8. AssetBundle _assetBundle = rootBundle;
  9. /// 翻译字典选项
  10. ///
  11. /// [locale] 语言
  12. ///
  13. /// [builder] 字典建造器
  14. class FISTrKeybookOption {
  15. const FISTrKeybookOption(this.locale, this.builder);
  16. final Locale locale;
  17. final FTrKeybookBuilder builder;
  18. /// 中文字典建造器
  19. static final FISTrKeybookOption ChineseOption = FISTrKeybookOption(
  20. CHINESE_LOCALE,
  21. () => _buildInnerBoook(CHINESE_LOCALE),
  22. );
  23. /// 英文字典建造器
  24. static final FISTrKeybookOption EnglishOption = FISTrKeybookOption(
  25. ENGLISH_LOCALE,
  26. () => _buildInnerBoook(ENGLISH_LOCALE),
  27. );
  28. }
  29. /// 国际化翻译字典
  30. FISTrKeybook get fisI18nBook => FISI18n.ins.currentBook;
  31. /// 国际化
  32. class FISI18n {
  33. FISI18n._();
  34. static FISI18n? _singleton;
  35. /// 单例
  36. static FISI18n get ins {
  37. if (_singleton == null) {
  38. throw Exception("There aren't any instance of FI18n.");
  39. }
  40. return _singleton!;
  41. }
  42. late FISTrKeybook _currentBook;
  43. late FI18nLocaleUpdater _localeUpdater;
  44. final Map<Locale, FTrKeybookBuilder> _bookMap = {};
  45. /// 当前语言字典
  46. FISTrKeybook get currentBook => _currentBook;
  47. /// 当前是否中文
  48. bool get isCurrentChinese => currentBook.isCurrentChinese;
  49. /// 支持的语言
  50. List<Locale> get supportedLocales => _bookMap.keys.toList();
  51. /// 设置内置资源包
  52. static void setAssetBundle(AssetBundle bundle) {
  53. _assetBundle = bundle;
  54. }
  55. /// 初始化
  56. static Future<void> init(
  57. FI18nLocaleUpdater localeUpdater,
  58. List<FISTrKeybookOption> bookOptions,
  59. ) async {
  60. if (_singleton != null) {
  61. throw Exception("FI18n has been init.");
  62. }
  63. _singleton = FISI18n._();
  64. _singleton!._localeUpdater = localeUpdater;
  65. await _singleton!._buildInstance(bookOptions);
  66. }
  67. Future<void> _buildInstance(List<FISTrKeybookOption> bookOptions) async {
  68. for (var option in bookOptions) {
  69. if (_bookMap.containsKey(option.locale)) {
  70. throw Exception("FI18n init: The same locale value already exists.");
  71. }
  72. setKeyBook(option.locale, option.builder);
  73. }
  74. }
  75. /// 加载(初始语言,init之后)
  76. static Future<void> load(Locale locale) async {
  77. // 语言+国家 精准匹配
  78. var bookBuilder = _singleton!._bookMap[locale];
  79. // 语言匹配
  80. if (bookBuilder == null) {
  81. final matchKey = _singleton!._bookMap.keys.firstWhere(
  82. (x) => x.languageCode == locale.languageCode,
  83. orElse: () => ENGLISH_LOCALE,
  84. );
  85. bookBuilder = _singleton!._bookMap[matchKey];
  86. }
  87. if (bookBuilder == null) {
  88. throw Exception(
  89. "FISI18n load error: No book-builder match the target locale.");
  90. }
  91. _singleton!._currentBook = await bookBuilder();
  92. }
  93. /// 切换语言
  94. Future<Locale> switchLanguage([Locale? locale]) async {
  95. Locale matchLocale;
  96. if (locale == null) {
  97. // 顺序找下一个字典
  98. final keys = _bookMap.keys.toList();
  99. final curIdx = keys.indexOf(currentBook.locale);
  100. int nextIdx = curIdx + 1;
  101. if (nextIdx >= keys.length) nextIdx = 0;
  102. matchLocale = keys[nextIdx];
  103. } else {
  104. // 优先语言Code和国家Code双匹配,否则选语言Code匹配
  105. final langCodeMatchList =
  106. _bookMap.keys.where((x) => x.languageCode == locale.languageCode);
  107. if (langCodeMatchList.isEmpty) {
  108. // 无匹配
  109. throw Exception(
  110. "FI18n switchLanguage: No keybook found for the target locale.");
  111. }
  112. if (langCodeMatchList.length > 1) {
  113. // 查找双匹配
  114. matchLocale = langCodeMatchList.firstWhere(
  115. (x) => x.countryCode == locale.languageCode,
  116. orElse: () => langCodeMatchList.first,
  117. );
  118. } else {
  119. // 单匹配
  120. matchLocale = langCodeMatchList.first;
  121. }
  122. }
  123. FTrKeybookBuilder builder = _bookMap[matchLocale]!;
  124. _currentBook = await builder();
  125. _localeUpdater(matchLocale);
  126. return matchLocale;
  127. }
  128. /// 设置翻译字典(相同语言会覆盖)
  129. void setKeyBook(Locale locale, FTrKeybookBuilder bookBuilder) {
  130. _bookMap[locale] = bookBuilder;
  131. }
  132. /// 根据字典树翻译
  133. ///
  134. /// [keyTree] 字典树,以.分隔,例:common.loading
  135. String translate(String keyTree) {
  136. final tiers = keyTree.split('.');
  137. dynamic curr = currentBook;
  138. for (var key in tiers) {
  139. if (curr is IPropQueryable) {
  140. curr = curr.getProp(key);
  141. } else {
  142. return keyTree;
  143. }
  144. }
  145. return curr;
  146. }
  147. }
  148. Future<FISTrKeybook> _buildInnerBoook(Locale locale) async {
  149. final code = locale.toCodeString();
  150. final assetKey = "assets/languages/$code.json";
  151. final text = await _assetBundle.loadString(assetKey, cache: false);
  152. final book = FISTrKeybook.createFromJson(text);
  153. return book;
  154. }