import 'dart:convert'; import 'package:flutter/services.dart'; import 'package:flutter/material.dart'; class AppLocalizations { final Locale locale; Map _localizedStrings = {}; AppLocalizations(this.locale); static AppLocalizations of(BuildContext context) { return Localizations.of(context, AppLocalizations)!; } static const LocalizationsDelegate delegate = _AppLocalizationsDelegate(); Future load() async { try { String jsonString = await rootBundle.loadString( 'assets/languages/${locale.languageCode}-${locale.countryCode}.json', ); Map jsonMap = json.decode(jsonString); _localizedStrings = jsonMap; return true; } catch (e) { debugPrint('❌ [AppLocalizations] 加载语言文件失败: $e'); return false; } } String translate(String key) { final keys = key.split('.'); dynamic value = _localizedStrings; for (final k in keys) { if (value is Map) { value = value[k]; } else { return key; } } return value?.toString() ?? key; } } class _AppLocalizationsDelegate extends LocalizationsDelegate { const _AppLocalizationsDelegate(); @override bool isSupported(Locale locale) { return ['zh', 'en'].contains(locale.languageCode); } @override Future load(Locale locale) async { final localizations = AppLocalizations(locale); await localizations.load(); return localizations; } @override bool shouldReload(_AppLocalizationsDelegate old) => false; }