我正在尝试使用bloc更改flutter应用程序的主题。 但是自从状态改变后第二次出现问题。
状态仍处于更新状态,但用户界面未更改,builder方法未再次运行
我的日志:
Performing hot restart...
Syncing files to device iPhone 11...
Restarted application in 1,386ms.
flutter: builder ThemeState
flutter: builder ThemeState
flutter: build
flutter: _ChangeThemeScreenState AppTheme.BlueDark
flutter: ThemeBloc AppTheme.BlueDark
flutter: ThemeBloc isThemeChange
flutter: builder ThemeState
flutter: _ChangeThemeScreenState AppTheme.BlueLight
flutter: ThemeBloc AppTheme.BlueLight
flutter: ThemeBloc isThemeChange
flutter: _ChangeThemeScreenState AppTheme.GreenDark
flutter: ThemeBloc AppTheme.GreenDark
flutter: ThemeBloc isThemeChange
我的代码:
class ThemeBloc extends Bloc<ThemeEvent, ThemeState> {
ThemeBloc() : super(ThemeState(themeData: appThemeData[AppTheme.GreenLight]));
@override
Stream<ThemeState> mapEventToState(
ThemeEvent event,
) async* {
print("ThemeBloc " + (event as ThemeChanged).theme.toString());
if (event is ThemeChanged) {
print("ThemeBloc " +'isThemeChange');
yield ThemeState(themeData: appThemeData[event.theme]);
}
}
}
class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (context) => ThemeBloc(),
child: BlocBuilder<ThemeBloc, ThemeState>(
builder: (context, state) {
print("builder " + state.toString());
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Bitradez',
routes: routes,
theme: state.themeData);
}
),
);
}
}
当标签页按钮
onTap: () {
print("_ChangeThemeScreenState " + itemAppTheme.toString());
BlocProvider.of<ThemeBloc>(context)
.add(ThemeChanged(theme: itemAppTheme));
},
答案 0 :(得分:1)
在您的ThemeState
类中,尝试将您的themeData
属性传递给道具,我很确定我遇到了和您前一段时间相同的问题。据我了解,您为props
设置的值是bloc
在决定是否重建窗口小部件时实际查看的内容。
我认为类似的方法应该起作用:
List<Object> get props => [themeData]
您显然仍然需要正确产生此状态。