app_localizations.dart 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import 'dart:convert';
  2. import 'package:flutter/material.dart';
  3. import 'package:flutter/services.dart';
  4. class AppLocalizations {
  5. final Locale locale;
  6. final Map<String, String> _strings;
  7. AppLocalizations(this.locale, this._strings);
  8. String get(String key) => _strings[key] ?? key;
  9. String getString(String key, {Map<String, String>? args}) {
  10. var value = _strings[key] ?? key;
  11. if (args != null) {
  12. for (final entry in args.entries) {
  13. value = value.replaceAll('\${${entry.key}}', entry.value);
  14. }
  15. }
  16. return value;
  17. }
  18. static AppLocalizations of(BuildContext context) {
  19. return Localizations.of<AppLocalizations>(context, AppLocalizations)!;
  20. }
  21. static Future<AppLocalizations> load(Locale locale) async {
  22. String langCode;
  23. if (locale.languageCode == 'zh') {
  24. langCode = locale.countryCode == 'TW' ? 'zh_TW' : 'zh_CN';
  25. } else {
  26. langCode = locale.languageCode;
  27. }
  28. final path = 'assets/i18n/$langCode.json';
  29. final jsonStr = await rootBundle.loadString(path);
  30. final json = jsonDecode(jsonStr) as Map<String, dynamic>;
  31. return AppLocalizations(
  32. locale,
  33. json.map((k, v) => MapEntry(k, v.toString())),
  34. );
  35. }
  36. static const LocalizationsDelegate<AppLocalizations> delegate =
  37. _AppLocalizationsDelegate();
  38. }
  39. class _AppLocalizationsDelegate
  40. extends LocalizationsDelegate<AppLocalizations> {
  41. const _AppLocalizationsDelegate();
  42. @override
  43. bool isSupported(Locale locale) => ['zh', 'en'].contains(locale.languageCode);
  44. @override
  45. Future<AppLocalizations> load(Locale locale) => AppLocalizations.load(locale);
  46. @override
  47. bool shouldReload(_AppLocalizationsDelegate old) => false;
  48. }