[英]Flutter bloc: BlocBuilder does not re-call builder method when stated state first time
I am trying to change the theme of my flutter app using bloc.我正在尝试使用 bloc 更改我的 flutter 应用程序的主题。 But I had a problem since the second time after the state was changed.
但是自从第二次更改 state 后,我遇到了一个问题。
Sate is still updated, but the UI has not changed, the builder method has not run again状态还在更新,但是 UI 没有改变,builder 方法没有再次运行
My log:我的日志:
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
my code:我的代码:
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);
}
),
);
}
}
when tab button when tab button
onTap: () {
print("_ChangeThemeScreenState " + itemAppTheme.toString());
BlocProvider.of<ThemeBloc>(context)
.add(ThemeChanged(theme: itemAppTheme));
},
In your ThemeState
class, try passing your themeData
property to the props, I am pretty sure that I had the same problem as you a while ago.在您的
ThemeState
class 中,尝试将您的themeData
属性传递给道具,我很确定我前一段时间遇到了同样的问题。 As far as I understand, the value that you set for the props
is what bloc
actually looks at when deciding whether to rebuild your widget or not.据我了解,您为
props
设置的值是bloc
在决定是否重建您的小部件时实际查看的值。
I think something like this should work:我认为这样的事情应该有效:
List<Object> get props => [themeData]
You obviously still need yield this state correctly.你显然仍然需要正确地输出这个 state。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.