Flutter Bloc State Management

Flutter Bloc is the powerful library in flutter to manage the state across the widgets for flutter applications. You can use it to handle all the possible states of your application in an easy way .So in this tutorial we will learn about the flutter_bloc package which is most popular now-days.

What is flutter bloc?

Flutter bloc is one of the best State managements for flutter Applications. You can use it to handle the states in an easy way in your flutter application. This library is mostly used, and anyone can easily understand no matter what your level is. An intermediate or experience can learn quickly. Its documentation is also very good to understand.

Example using flutter bloc

Let’s create an example using flutter bloc. So, in the below example we are going to create an application in which we will check the internet connection continuously. When the internet connection changes it will reflect on the spot, so for that we will show a Snack bar to display the message that internet got ON or OFF.

Add these following two libraries in your pubspec.yaml file:

  flutter_bloc: ^8.1.3
  connectivity_plus: ^4.0.1

1 Create a class InternetState

This will be used to get the states ,like internet connected, lost of initial state. And the class is abstract because we will not use to create its instance.


abstract class InternetState{}

//which state we needed to show
class InternetInitialState extends InternetState{}
class InternetLostState extends InternetState{}
class InternetGainedState extends InternetState{}

2 Create a class InternetEvent

This class will handle the event that can be happen like either lost or connected.


abstract class InternetEvent{}

//used for user interaction
class InternetLostEvent extends InternetEvent{}
class InterNetGainedEvent extends InternetEvent{}

3 Create a Bloc class

This is the businesses logic class that contains the business logics. We will use it to emit the events where we want to use, like in this case we will check internet connectivity in this class and will return the state of the event. So this class will be used inside any widget to get the logics.


import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:demo_test/Bloc/InternetEvent.dart';
import 'package:demo_test/Bloc/InternetState.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

class InternetBloc extends Bloc<InternetEvent, InternetState> {
  StreamSubscription<ConnectivityResult>? subscription;

  InternetBloc() : super(InternetInitialState()) {
    on<InternetLostEvent>((event, emit) => emit(InternetLostState()));
    on<InterNetGainedEvent>((event, emit) => emit(InternetGainedState()));

    //check internet connectivity
    subscription = Connectivity()
        .onConnectivityChanged
        .listen((ConnectivityResult result) {
      if (result == ConnectivityResult.mobile ||
          result == ConnectivityResult.wifi ||
          result == ConnectivityResult.ethernet ||
          result == ConnectivityResult.vpn) {
        add(InterNetGainedEvent()); //connected
      }else{
        add(InternetLostEvent());  //lost event
      }
    });
  }

  @override
  Future<void> close() {
    subscription?.cancel();
    return super.close();
  }
}

4 Using the bloc into the widget

Finally this is the widget where we will use the bloc architecture after completing all the process. But before that you have declare the BlocProvider in the main.dart so we can use it anywhere in the app, because the MaterialApp is the entry point of the app.

Add the BlocProvider into the main.dart:

main.dart

import 'package:demo_test/Bloc/InternetBloc.dart';
import 'package:demo_test/Home.dart';
import 'package:demo_test/InternetCheck.dart';
import 'package:demo_test/UserPrvider.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:provider/provider.dart';

void main() {
  runApp(BlocProvider(
    create: (context) => InternetBloc(),
    child: MyApp(),
  ));
}

class MyApp extends StatelessWidget {
  final GlobalKey<ScaffoldMessengerState>? scaffoldMessengerKey;
  const MyApp({super.key, this.scaffoldMessengerKey});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: InternetCheck(),
    );
  }
}

InternetCheck.dart


import 'package:demo_test/Bloc/InternetBloc.dart';
import 'package:demo_test/Bloc/InternetState.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

class InternetCheck extends StatelessWidget {
  const InternetCheck({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: SafeArea(
            child: Center(
                child: BlocConsumer<InternetBloc, InternetState>(
      listener: (context, state) {
        if (state is InternetGainedState) {
          ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
            content: Text("connected!", style: TextStyle(fontSize: 22),),
            backgroundColor: Colors.green,
          ));
        } else if (state is InternetLostState) {
          ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
            content: Text("connection Lost!", style: TextStyle(fontSize: 22),),
            backgroundColor: Colors.red,
          ));
        }
      },
      builder: (context, state) {
        if (state is InternetGainedState) {
          return const Text("connected!", style: TextStyle(fontSize: 22),);
        } else if (state is InternetLostState) {
          return const Text("connection lost!", style: TextStyle(fontSize: 22),);
        } else {
          return const Text("checking....!", style: TextStyle(fontSize: 22),);
        }
      },
    ))));
  }
}

Suggestions:

Provider State Management In Flutter

GetX State Management

Donโ€™t miss new tips!

We donโ€™t spam! Read our [link]privacy policy[/link] for more info.

Leave a Comment

Translate ยป
Scroll to Top