Switch themes in flutter apps using cubit(BLOC)

Sayurusadaru
3 min readMar 25, 2021

--

Throughout this article, we will discover step by step how to facilitate users to switch between themes. For that, we will use Cubit which, is a subset of the BloC pattern.

Step 1: Organize your Project

The first and most dominant part is correctly organizing your project structure. It will help you a lot when expanding your project. Following is my way of organizing the project.

Step 2: Add flutter_bloc and bloc packages to your app

Pubspec.yaml file with relevant dependencies

Step 3: Creating custom themes

Now we want to create custom themes for our app. I will create all these in the themeData.dart file.

I had created two custom themes called LightAppTheme, DarkAppTheme and stored them as an enum. Then I used a map to assign values to our themes using a ThemeData class.

Step 4: Creating Cubit for switch themes

In the next step, we want to implement Cubit for switch between themes. before that, you need to create switch_cubit.dart and switch_state.dart files.

Step 4.1: Then inside the switch_state.dart file you need to code as follows,

I had created SwitchState class to define the states of the app with a final boolean isDarkThemeOn and ThemeData called theme. isDarkThemeOn will toggle true/false when we called the copyWith function. we can use the theme field when we changing the theme in our app

Step 4.2: Code the switch_cubit.dart file

I had created the cubit as above and defined its initial state as isDarkThemeOn: true. Then I had created a separate function named as toggleSwitch which takes boolean input and emits a state change with that input.

Step 5: Creating HomeScreen class

Then we want to create a HomePage for our app with a switch widget that facilitates users to select their preferred theme.

In the AppBar widget, I had implemented the Switch widget with BlocBuilder wrapping around it. With BlocBuilder we can access the isDarkThemeOn state. In the onChanged argument, we can call the toggleSwitch function with a new value that we created earlier.

We can access the themes created in themeData.dart by using Theme.of(context).

Step 5: Change the main.dart

Then we need to wrap the MaterialApp Widget inside a BlocProvider to provide BLoC to its children. Then again we need to wrap the MaterialApp inside a BlocBuilder. After that, we can assign the theme state to the theme argument in the MaterialApp widget.

The final app looks like this.

Final word

To easier the workflow you can use the BloC extension which comes for the Vscode, android studio. You can learn more about BloC from its documentation to get a better understanding.

🔴 Above project is down and with the newer version of flutter and the bloc package this will not work. Follow this link to access the updated article or access the updated code here.

--

--

Sayurusadaru

UI designer, App developer, hobby photographer. working as a freelancer