import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; class AppLocalizations { final Locale locale; final Map _strings; AppLocalizations(this.locale, this._strings); String get(String key) => _strings[key] ?? key; String getString(String key, {Map? args}) { var value = _strings[key] ?? key; if (args != null) { for (final entry in args.entries) { value = value.replaceAll('\${${entry.key}}', entry.value); } } return value; } static AppLocalizations of(BuildContext context) { return Localizations.of(context, AppLocalizations)!; } static Future load(Locale locale) async { String langCode; if (locale.languageCode == 'zh') { langCode = locale.countryCode == 'TW' ? 'zh_TW' : 'zh_CN'; } else { langCode = locale.languageCode; } final path = 'assets/i18n/$langCode.json'; final jsonStr = await rootBundle.loadString(path); final json = jsonDecode(jsonStr) as Map; return AppLocalizations( locale, json.map((k, v) => MapEntry(k, v.toString())), ); } static const LocalizationsDelegate delegate = _AppLocalizationsDelegate(); } class _AppLocalizationsDelegate extends LocalizationsDelegate { const _AppLocalizationsDelegate(); @override bool isSupported(Locale locale) => ['zh', 'en'].contains(locale.languageCode); @override Future load(Locale locale) => AppLocalizations.load(locale); @override bool shouldReload(_AppLocalizationsDelegate old) => false; }