create enum
enum AppTheme { Light, Dark }
final appThemeData = {
AppTheme.Light: ThemeData(
brightness: Brightness.light,
textTheme: GoogleFonts.latoTextTheme(),
),
AppTheme.Dark: ThemeData(
brightness: Brightness.dark,
textTheme: GoogleFonts.latoTextTheme(),
),
};
create bloc for the theme changing
class AppThemeState extends Equatable {
final AppTheme appTheme;
AppThemeState({this.appTheme});
@override
List<Object> get props => [appTheme];
}
abstract class AppThemeEvent extends Equatable {
const AppThemeEvent();
@override
List<Object> get props => [];
}
class AppThemeChanged extends AppThemeEvent {
final bool isLight;
const AppThemeChanged({this.isLight});
@override
List<Object> get props => [isLight];
}
class AppThemeBloc extends Bloc<AppThemeEvent, AppThemeState> {
@override
AppThemeState get initialState => AppThemeState(appTheme: AppTheme.Light);
@override
Stream<AppThemeState> mapEventToState(AppThemeEvent event) async* {
if (event is AppThemeChanged) {
if (event.isLight) {
PrefsUtil.saveIsLightTheme(true);
yield AppThemeState(appTheme: AppTheme.Light);
} else {
PrefsUtil.saveIsLightTheme(false);
yield AppThemeState(appTheme: AppTheme.Dark);
}
}
}
}
main screen
class _MainAppState extends State<MainApp> {
@override
Widget build(BuildContext context) {
return BlocProvider<AppThemeBloc>(
create: (context) => AppThemeBloc(),
child: BlocBuilder<AppThemeBloc, AppThemeState>(
builder: (BuildContext context, AppThemeState state) {
return MaterialApp(
home: RouterHelper.splashBuilder(context),
theme: appThemeData[state.appTheme],
);
},
),
);
}
}
create the theme
BlocProvider.of<AppThemeBloc>(context).add(AppThemeChanged(isLight: !PrefsUtil.getIsLightTheme()));