Reputation: 159
I am trying to change the theme of my flutter app using bloc. But I had a problem since the second time after the state was changed.
Sate is still updated, but the UI has not changed, the builder method has not run again
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
onTap: () {
print("_ChangeThemeScreenState " + itemAppTheme.toString());
BlocProvider.of<ThemeBloc>(context)
.add(ThemeChanged(theme: itemAppTheme));
},
Upvotes: 0
Views: 1720
Reputation: 702
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. 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.
I think something like this should work:
List<Object> get props => [themeData]
You obviously still need yield this state correctly.
Upvotes: 3