65 lines
1.6 KiB
Dart
65 lines
1.6 KiB
Dart
import 'dart:convert';
|
|
import 'package:flutter/services.dart';
|
|
import 'package:flutter/material.dart';
|
|
|
|
class AppLocalizations {
|
|
final Locale locale;
|
|
Map<String, dynamic> _localizedStrings = {};
|
|
|
|
AppLocalizations(this.locale);
|
|
|
|
static AppLocalizations of(BuildContext context) {
|
|
return Localizations.of<AppLocalizations>(context, AppLocalizations)!;
|
|
}
|
|
|
|
static const LocalizationsDelegate<AppLocalizations> delegate = _AppLocalizationsDelegate();
|
|
|
|
Future<bool> load() async {
|
|
try {
|
|
String jsonString = await rootBundle.loadString(
|
|
'assets/languages/${locale.languageCode}-${locale.countryCode}.json',
|
|
);
|
|
Map<String, dynamic> 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<String, dynamic>) {
|
|
value = value[k];
|
|
} else {
|
|
return key;
|
|
}
|
|
}
|
|
|
|
return value?.toString() ?? key;
|
|
}
|
|
}
|
|
|
|
class _AppLocalizationsDelegate extends LocalizationsDelegate<AppLocalizations> {
|
|
const _AppLocalizationsDelegate();
|
|
|
|
@override
|
|
bool isSupported(Locale locale) {
|
|
return ['zh', 'en'].contains(locale.languageCode);
|
|
}
|
|
|
|
@override
|
|
Future<AppLocalizations> load(Locale locale) async {
|
|
final localizations = AppLocalizations(locale);
|
|
await localizations.load();
|
|
return localizations;
|
|
}
|
|
|
|
@override
|
|
bool shouldReload(_AppLocalizationsDelegate old) => false;
|
|
}
|