📅  最后修改于: 2022-03-11 14:55:37.542000             🧑  作者: Mango
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class AppLocalizations {
final Locale locale;
AppLocalizations (this.locale);
static AppLocalizations? of(BuildContext context) {
return Localizations.of(context, AppLocalizations);
}
static const LocalizationsDelegate delegate =
_AppLocalizationsDelegate();
late Map _localizedStrings;
Future load() async {
String jsonString =
await rootBundle.loadString('lang/${locale.languageCode}.json');
Map jsonMap = json.decode(jsonString);
_localizedStrings = jsonMap.map((key, value) {
return MapEntry(key, value.toString());
});
return true;
}
String translate(String key) {
return _localizedStrings[key]!;
}
}
class _AppLocalizationsDelegate
extends LocalizationsDelegate {
const _AppLocalizationsDelegate();
@override
bool isSupported(Locale locale) {
return ['en', 'vi'].contains(locale.languageCode);
}
@override
Future load(Locale locale) async {
AppLocalizations localizations = new AppLocalizations(locale);
await localizations.load();
return localizations;
}
@override
bool shouldReload(_AppLocalizationsDelegate old) => false;
}