A Beginners Guide to Dynamic Theme in Flutter using BLoC

A Beginners Guide to Dynamic Theme in Flutter using BLoC

In Flutter, we have an option of BLoC(Business Logic Component) for clean and elegant state management. 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

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:

  1. StreamController
  2. Stream
  3. Sink

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.

import 'dart:async';

class ThemeBloc {
  final _themeStreamController = StreamController<bool>();
  get changeTheTheme => _themeStreamController.sink.add;
  get darkThemeIsEnabled => _themeStreamController.stream;
}

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.

import 'package:flutter/material.dart';
import 'theme.bloc.dart';

class HomePage extends StatelessWidget {

  final bool isDarkThemeEnabled;
  final ThemeBloc bloc;

  HomePage(this.isDarkThemeEnabled, this.bloc);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Robo World"),
        centerTitle: true,
      ),
      body: ListView.builder(
        itemCount: 20,
        itemBuilder: (BuildContext context, index) {
          return ListTile(
            title: Text("User ${index+1}"),
            leading: Image.network('https://robohash.org/user$index}'),
            trailing: Icon(Icons.edit),
          );
        },
      ),
      drawer: Drawer(
        child: ListView(
          children: <Widget>[
            ListTile(
              title: Text("Dark Theme"),
              trailing: Switch(
                value: isDarkThemeEnabled,
                onChanged: bloc.changeTheTheme
              ),
            )
          ],
        ),
      ),
    );
  }
}

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 filefor starting the app accordingly. Here’s the main.dart file.

import 'package:dynamic_theme/home_page.dart';
import 'package:dynamic_theme/theme.bloc.dart';
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return StreamBuilder(
      initialData: false,
      stream: bloc.darkThemeIsEnabled,
      builder: (context, snapshot) {
        return MaterialApp(
          theme: snapshot.data ? ThemeData.dark() : ThemeData.light(),
          home: new HomePage(snapshot.data, bloc)
        );
      }
    );
  }
}

final bloc = ThemeBloc();

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.

A Beginners Guide to Dynamic Theme in Flutter using BLoC

A Beginners Guide to Dynamic Theme in Flutter using BLoC

A Beginners Guide to Dynamic Theme in Flutter using BLoC

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.

Good Bye!!!

flutter dart mobile-apps ios

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Google's Flutter 1.20 stable announced with new features - Navoki

Google has announced new flutter 1.20 stable with many improvements, and features, enabling flutter for Desktop and Web

How To Succeed In Mobile App Wireframe Design?

This article covers everything about mobile app wireframe design: what to do and what not, tools used in designing a mobile or web app wireframe, and more.

How long does it take to develop/build an app?

This article covers A-Z about the mobile and web app development process and answers your question on how long does it take to develop/build an app.

Top 25 Flutter Mobile App Templates in 2020

Flutter has been booming worldwide from the past few years. While there are many popular mobile app development technologies out there, Flutter has managed to leave its mark in the mobile application development world. In this article, we’ve curated the best Flutter app templates available on the market as of July 2020.

Best Mobile App Development Company | Android and iOS Apps

iPrism Tech is a one of the best and offshore mobile app development company in India, Saudi Arabia and USA. We are a major providers of android, iphone and ipad mobile app development services at economical prices.