3分钟
07 国际化-3
说完了 delegate , 接下来就是 Localizations
了。在上面的流程图中可以看到, Localizations 提供一个 override
方法构建 Localizations
,这个方法中可以设置 locale,而我们需要的正是实时的动态切换语言显示。
如下代码,我们创建一个 GSYLocalizations
的 Widget,通过 StoreBuilder
绑定 Store,然后通过 Localizations.override
包裹我们需要构建的页面,将 Store 中的 locale
和 Localizations 的 locale
绑定起来。
class GSYLocalizations extends StatefulWidget {
final Widget child;
GSYLocalizations({Key key, this.child}) : super(key: key);
@override
State<GSYLocalizations> createState() {
return new _GSYLocalizations();
}
}
class _GSYLocalizations extends State<GSYLocalizations> {
@override
Widget build(BuildContext context) {
return new StoreBuilder<GSYState>(builder: (context, store) {
///通过 StoreBuilder 和 Localizations 实现实时多语言切换
return new Localizations.override(
context: context,
locale: store.state.locale,
child: widget.child,
);
});
}
}
如下代码,最后将 GSYLocalizations
使用到 MaterialApp
中。通过 store.dispatch
切换 Locale
即可。
@override
Widget build(BuildContext context) {
/// 通过 StoreProvider 应用 store
return new StoreProvider(
store: store,
child: new StoreBuilder<GSYState>(builder: (context, store) {
return new MaterialApp(
///多语言实现代理
localizationsDelegates: [
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GSYLocalizationsDelegate.delegate,
],
locale: store.state.locale,
supportedLocales: [store.state.locale],
routes: {
HomePage.sName: (context) {
///通过 Localizations.override 包裹一层。---这里
return new GSYLocalizations(
child: new HomePage(),
);
},
});
}),
);
}
///切换主题
static changeLocale(Store<GSYState> store, int index) {
Locale locale = store.state.platformLocale;
switch (index) {
case 1:
locale = Locale('zh', 'CH');
break;
case 2:
locale = Locale('en', 'US');
break;
}
store.dispatch(RefreshLocaleAction(locale));
}
最后的最后,在改变时记录状态,在启动时取出后dispatch
,至此主题和多语言设置完成。
学员评价