Flutter ecosystem is really good for building high-quality apps with a lot of features. State management is one of the important aspect of high-quality and it is always a challenging task for every software developer irrespective of the type of application he/she is building. State management becomes more complex as the complexity of the application increases. In Flutter, we have an option of BLoC(Business Logic Component) for clean and elegant state management.
BLoC pattern is a very robust technique for state management as it uses Streams as it’s core and it is not at all a difficult task to implement BLoC in any application. Dynamic Theme refers to changing the theme of the app based on the user’s preference at runtime. This technique is used for good user experience as user always has a choice to switch the theme. When we talk about BLoC pattern in Flutter, 3 things come in our mind:
If you are not familiar with Streams and BLoC pattern, then I would recommend you to learn those from this resource.
First of all we will be creating a new file in lib folder for BLoC logic. This file will contain the logic part(main core of the BLoC pattern logic) required for our application.
Here, we are creating StreamController of bool because we want to pass the boolean data in our stream. After that, we are implementing the changeTheTheme() and darkThemeIsEnabled() functions using the sink and stream respectively.
In the home_page.dart file, we are just creating a scaffold and inside that scaffold, we are just rendering a list with random images in the list tile. The data is rendered for demo purpose. A drawer is created and a switch is given in order to switch between the light and the dark theme.
Now, after all these files in place, we are required to setup the main.dart file for starting the app accordingly. Here’s the main.dart file.
In the main.dart file, we are using a StreamBuilder widget to deal with the Streams which are introduced due to BLoC pattern.
Here are the screenshots of the app which we have built.
This app is a demo app which can be implemented for performing dynamic theme behaviour in your app using BLoC pattern for State Management. The dynamic theme functionality gives a good User Experience as the user has it’s own choice to switch between the different colour themes.
The Final Words
Dynamic Theme is always a good experience for the user and because of this, it is really awesome to implement dynamic theme in apps. BLoC Pattern is a very robust technique for state management in flutter which can be used to scale any app at any level. So, we can use BLoC Pattern for state management as well as for implementing dynamic themes.