I am new in Flutter and bloc. I am making a app with bloc state management that can change the theme as the system theme changed. Now it work fine but I need switch that can override the theme. How can I implement that? I am making this app by watching a youtube tutorial. Is that anyway to create that switch that can change the theme.
Theme Cubit
class ThemeCubit extends Cubit<ThemeState> {
ThemeCubit() : super(ThemeState(themeMode: ThemeMode.light)) {
updateAppTheme();
}
void updateAppTheme() {
final Brightness currentBrightness = AppTheme.currentSystemBrightness;
currentBrightness == Brightness.light
? _setTheme(ThemeMode.light)
: _setTheme(ThemeMode.dark);
}
void _setTheme(ThemeMode themeMode) {
AppTheme.setStatusBarAndNavigationBarColor(themeMode);
emit(ThemeState(themeMode: themeMode));
}
}
Theme_state
class ThemeState {
final ThemeMode themeMode;
ThemeState({@required this.themeMode});
}
Here is the code of main.dart
void main() {
Bloc.observer = AppBlocObserver();
runApp(DevicePreview(
builder: (context) => App(),
enabled: false,
plugins: [
const ScreenshotPlugin(),
],
));
}
class App extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MultiBlocProvider(
providers: [
BlocProvider<ThemeCubit>(
create: (context) => ThemeCubit(),
),
],
child: MchatsApp(),
);
}
}
class MchatsApp extends StatefulWidget {
const MchatsApp({
Key key,
}) : super(key: key);
@override
_MchatsAppState createState() => _MchatsAppState();
}
class _MchatsAppState extends State<MchatsApp> with WidgetsBindingObserver {
@override
void initState() {
WidgetsBinding.instance.addObserver(this);
super.initState();
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
@override
void didChangePlatformBrightness() {
context.read<ThemeCubit>().updateAppTheme();
super.didChangePlatformBrightness();
}
@override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (context, constraints) {
return OrientationBuilder(
builder: (context, orientation) {
SizerUtil().init(constraints, orientation);
return MaterialApp(
locale: DevicePreview.locale(context),
builder: DevicePreview.appBuilder,
title: Strings.appTitle,
theme: AppTheme.lightTheme,
darkTheme: AppTheme.darkTheme,
themeMode: context.select(
(ThemeCubit themeCubit) => themeCubit.state.themeMode),
debugShowCheckedModeBanner: false,
initialRoute: AppRouter.root,
onGenerateRoute: AppRouter.onGenerateRoute,
);
},
);
},
);
}
}