Reputation: 1
Theme change container Switch have opposite value. I just started app and I can't change a vlaue of switch. I used a basic equatable cubit to do a logic of changing theme and in this cubit there is saving data to shared_preferences
class _AppState extends State<App> {
late SharedPreferences prefs;
bool? _isDark = false;
void loadPrefs() async {
prefs = await SharedPreferences.getInstance();
_isDark = prefs.getBool('theme');
}
@override
void initState() {
loadPrefs();
super.initState();
}
@override
Widget build(BuildContext context) {
return MultiBlocProvider(
providers:[
BlocProvider(
create: (context) => ThemeCubit(),
),
BlocProvider(
create: (context) => FormControlCubit()
)
],
child:BlocBuilder<ThemeCubit, ThemeState>(
builder: (context, state) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
theme: _isDark ?? state.isDark ? darkTheme : lightTheme,
home: const AuthGate(idx: 0,),
);
},
)
);
}
}
Upvotes: 0
Views: 44
Reputation: 3327
There are some notes you should keep in mind:
When overriding initState
method call the super method firstly at the first line and vice versa in disposing you should destroy the child first, so you call super.dispose
at the last line.
If you are managing the theme using cubit, do not extend Equatable
or mix EquatableMixin
with the super class of the states, specially if you manage the theme with one state.
example:
sealed class ThemeManagerStates exetends Equatable{
// and you override the props getter here.
}
final class ThemeChangedState extends Equatable{
// and you override the props getter here.
}
When you extend Equatable
, no symmetric states will be emitted sequentially (one after another).
So, do not use equatable for such state in which user might change the theme many many times sequentially (or you might meet a tester who likes stress testing).
Upvotes: 0