Search code examples
flutterdartbloc

Switching theme with BloC. Am I doing right?


Hello I am trying to change theme with BloC. But not sure if it is best practice.

Here is my switch_theme_cubit.dart

class ThemeCubit extends Cubit<ThemeData> {
  ThemeCubit() : super(AppTheme.lightTheme);

  void switchTheme() {
    state == AppTheme.lightTheme
        ? emit(AppTheme.darkTheme)
        : emit(AppTheme.lightTheme);
  }
}

And MaterialApp part of main.dart

class App extends StatelessWidget {
  const App({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MultiBlocProvider(
      providers: [
        BlocProvider(create: (context) => InternetConnectivityCubit()),
        BlocProvider(create: (context) => CounterCubit()),
        BlocProvider(create: (context) => ThemeCubit())
      ],
      child: BlocBuilder<ThemeCubit, ThemeData>(
        builder: (context, state) {
          return MaterialApp(
            title: Strings.appTitle,
            theme: state,
            debugShowCheckedModeBanner: false,
            initialRoute: AppRouter.homeScreen,
            onGenerateRoute: AppRouter.onGenerateRoute,
          );
        },
      ),
    );
  }
}

It looks like this (the first part of the gif in the readme). Am I doing right ?


Solution

  • Yes, technically, this is absolutely correct.

    I would suggest you make your mode a three-state. Light, Dark and System Default.

    When I set my device to dark mode, I want all my apps to go to dark mode by default. I don't want to open all 37 apps and find the setting and switch them individually. The default should be that if I have not set it explicitely, it will take the value from what I have set in my system settings.