Я новичок в флаттер и пытаюсь интернационализировать контент.Я хочу следовать «простому» подходу, предложенному в учебнике по флаттеру .
Мой вопрос касается производительности такой реализации, учитывая, что мне кажется, что каждый разлокализованная строка должна быть визуализирована сначала, соответствующая локаль ее контекста извлекается (с Localizations.of<MyLocalizations>(context, MyLocalizations)
), а затем получается локализованное значение.
Я немного изменил реализацию следующим образом, чтобы избежать "магических строк""и заставить себя явно перевести любую новую строку на все языки:
/// Instead of using directly the equivalent underlying string for a language code, consider using
/// [LanguageCodes] to obtain the locales code [String], which exposes the languages implemented for the app, such as
/// [LanguageCodes.en] (default) and [LanguageCodes.es].
class LanguageCodes {
/// Default private constructor to prevent instantiation of this class.
const LanguageCodes._();
/// English
static const String en = 'en';
/// Spanish
static const String es = 'es';
/// TRUSTY supported language codes
static const List<String> _codes = [en, es];
/// Whether the given locale code is defined in the app.
static bool isSupported(String languageCode) => _codes.contains(languageCode);
}
/// Class which encapsulates the handling of localized values.
class MyLocalizationsDelegate extends LocalizationsDelegate<MyLocalizations> {
/// Default explicit constructor
const MyLocalizationsDelegate();
@override
bool isSupported(Locale locale) => LanguageCodes.isSupported(locale.languageCode);
@override
Future<MyLocalizations> load(Locale locale) {
// An async "load" operation is not needed to produce an instance of MyLocalizations.
return SynchronousFuture<MyLocalizations>(new MyLocalizations(locale));
}
@override
bool shouldReload(MyLocalizationsDelegate old) => false;
}
/// Class containing the current locale of the app.
class MyLocalizations {
/// Current locale
final Locale _locale;
/// Default explicit constructor
const MyLocalizations(this._locale);
/// Shorthand method to access the [Locale] of the given context.
static Locale localeOf(BuildContext context) {
return Localizations.of<MyLocalizations>(context, MyLocalizations)._locale;
}
}
/// The [LocalizedStrings] class is designed to be the single top level container for localized strings.
/// Method [LocalizedStrings.of] is to be used to retrieve the underlying string corresponding to the desired locale
/// of the current context.
class LocalizedStrings {
/// Log In
static const LocalizedStrings logIn = const LocalizedStrings._({
LanguageCodes.en: "Log In",
LanguageCodes.es: "Iniciar Sesión",
});
/// Localized values
final Map<String, String> _values;
/// Default private constructor to prevent instantiation of this class.
const LocalizedStrings._(this._values);
/// Gets the underlying localized [String] corresponding to the given [BuildContext]
String of(BuildContext context) {
return _values[MyLocalizations.localeOf(context).languageCode];
}
}
При использовании локализованной строки в приложении, например," logIn ", она будет выглядеть следующим образом:
LocalizedStrings.logIn.of(context);