我将ThemeBloc作为父对象,因为我想动态更改应用程序的主题。它可以工作,但是我只是想向应用程序添加本地化。而且这没有按预期工作。在应用程序启动时,MaterialApp无法识别系统语言。但是当我更改语言时,MaterialApp会正确识别它。
我做了一个实验。我删除了BlocBuilder并将MaterialApp设置为根小部件。然后,始终检测到系统语言。
颤抖的医生输出
Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel master, v1.5.9-pre.69, on Linux, locale en_US.UTF-8)
[✓] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
[✓] Android Studio (version 3.4)
[✓] Android Studio (version 3.3)
[✓] IntelliJ IDEA Community Edition (version 2019.1)
[✓] Connected device (1 available)
• No issues found!
不良行为:
void main() async {
Fimber.plantTree(DebugTree());
await DI.setup();
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
AuthBloc authBloc = DI.inject();
ThemeBloc themeBloc = DI.inject();
@override
void initState() {
authBloc.dispatch(InitAuthEvent());
themeBloc.dispatch(InitThemeEvent());
super.initState();
}
@override
Widget build(BuildContext context) {
return BlocBuilder(
bloc: themeBloc,
builder: (_, themeState) {
if (themeState is InitThemeState) {
return MaterialApp(home: SplashScreen());
} else if (themeState is AppThemeState) {
return MaterialApp(
localizationsDelegates: [
AppLocalizationsDelegate(),
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate
],
supportedLocales: AppLocalizations.supportedLocales,
localeResolutionCallback: (locale, supportedLocales) {
if (AppLocalizations.isSupported(locale)) {
return Locale(locale.languageCode);
} else {
return Locale('en');
}
},
theme: stateToTheme(themeState),
home: _InitWidget()
);
}
},
);
}
ThemeData stateToTheme(AppThemeState state) {
switch (state.currentTheme) {
case AppTheme.light:
return ThemeData.light();
case AppTheme.dark:
return ThemeData.dark();
}
return null;
}
}
良好行为:
class _MyAppState extends State<MyApp> {
AuthBloc authBloc = DI.inject();
ThemeBloc themeBloc = DI.inject();
@override
void initState() {
authBloc.dispatch(InitAuthEvent());
themeBloc.dispatch(InitThemeEvent());
super.initState();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
localizationsDelegates: [
AppLocalizationsDelegate(),
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate
],
supportedLocales: AppLocalizations.supportedLocales,
localeResolutionCallback: (locale, supportedLocales) {
if (AppLocalizations.isSupported(locale)) {
return Locale(locale.languageCode);
} else {
return Locale('en');
}
},
home: _InitWidget()
}
}
``