我为Flutter应用实现了应用本地化。一切正常。但是有一个问题。在AppLocalization类的load方法中,我调用返回Future的方法,这些方法会启动我的翻译。
现在,当load方法启动我的翻译时,将调用我主页的build方法,该方法使用旧的localizables完成构建。如果我转到另一个页面,然后返回该页面,因为可本地化功能已经被初始化。
为防止这种情况,我需要暂停不确定该页面的构建方法。或在AppLocalization类的load函数末尾重新触发build方法。我无法导航到AppLocalization类中的该页面,因为我无权在那里建立上下文。
有人在他们的项目中遇到过类似的挑战吗?
答案 0 :(得分:0)
您需要以如下方式编写AppLocalization
和AppLocalizationDelegate
类:
class AppLocalization {
AppLocalization(this.localeName);
static const AppLocalizationDelegate delegate =
AppLocalizationDelegate();
static Future<AppLocalization> load(Locale locale) {
final String name = locale.countryCode.isEmpty ? locale.languageCode : locale.toString();
final String localeName = Intl.canonicalizedLocale(name);
return initializeMessages(localeName).then((_) {
Intl.defaultLocale = localeName;
return AppLocalization(localeName);
});
}
static AppLocalization of(BuildContext context) {
return Localizations.of<AppLocalization>(context, AppLocalization);
}
final String localeName;
String pageHomeWelcome(String name) {
return Intl.message(
'Welcome $name',
name: 'pageHomeWelcome',
args: [name],
);
}
// ... other key getters here
}
class AppLocalizationDelegate extends LocalizationsDelegate<S> {
const AppLocalizationDelegate();
List<Locale> get supportedLocales {
return const <Locale>[
Locale('de', ''), Locale('en', ''),
];
}
@override
bool isSupported(Locale locale) => _isSupported(locale);
@override
Future<AppLocalization> load(Locale locale) => AppLocalization.load(locale);
@override
bool shouldReload(AppLocalizationDelegate old) => false;
bool _isSupported(Locale locale) {
if (locale != null) {
for (Locale supportedLocale in supportedLocales) {
if (supportedLocale.languageCode == locale.languageCode) {
return true;
}
}
}
return false;
}
}
然后,在您的应用代码中定义localizationDelegates
和supportedLocales
:
import 'package:flutter_localizations/flutter_localizations.dart';
import 'l10n.dart'; // Where your AppLocalization and AppLocalizationDelegate classes are defined
// ...
new MaterialApp(
localizationsDelegates: [
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
AppLocalization.delegate
],
supportedLocales: AppLocalization.delegate.supportedLocales,
home: MyHomePage()
);
要更改应用的语言环境时,只需致电:
AppLocalization.load(Locale('de', 'DE'));
,它将自动重新加载。
有关整个设置的更多详细信息,您可以找到here。