State Management with Flutter BLoc Pattern - Expert

 

Bloc-to-Bloc Communication

 we have two options to communicate between bloc-to-bloc

1. Stream subscription

To understand this we have created two cubits first is the counter and the second is the internet cubit. we increment value if mobile connected with wifi and decrement when mobile connected with mobile data.

internet_state.dart
  part of 'internet_cubit.dart';

@immutable
abstract class InternetState {}

class InternetLoading extends InternetState {}

class InternetConnected extends InternetState {
  final ConnectionType connectionType;

  InternetConnected({@required this.connectionType});
}

class InternetDisconnected extends InternetState {}
  
internet_cubit.dart
  import 'dart:async';

import 'package:bloc/bloc.dart';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter_bloc_concepts/constants/enums.dart';
import 'package:meta/meta.dart';

part 'internet_state.dart';

class InternetCubit extends Cubit {
  final Connectivity connectivity;
  StreamSubscription connectivityStreamSubscription;

  InternetCubit({@required this.connectivity}) : super(InternetLoading()) {
    monitorInternetConnection();
  }

  StreamSubscription monitorInternetConnection() {
    return connectivityStreamSubscription =
        connectivity.onConnectivityChanged.listen((connectivityResult) {
      if (connectivityResult == ConnectivityResult.wifi) {
        emitInternetConnected(ConnectionType.Wifi);
      } else if (connectivityResult == ConnectivityResult.mobile) {
        emitInternetConnected(ConnectionType.Mobile);
      } else if (connectivityResult == ConnectivityResult.none) {
        emitInternetDisconnected();
      }
    });
  }

  void emitInternetConnected(ConnectionType _connectionType) =>
      emit(InternetConnected(connectionType: _connectionType));

  void emitInternetDisconnected() => emit(InternetDisconnected());

  @override
  Future close() {
    connectivityStreamSubscription.cancel();
    return super.close();
  }
}
  
counter_state.dart
  part of 'counter_cubit.dart';

class CounterState {
  int counterValue;
  bool wasIncremented;

  CounterState({
    @required this.counterValue,
    this.wasIncremented,
  });
}
  
counter_cubit.dart
  import 'package:bloc/bloc.dart';

import 'package:meta/meta.dart';

part 'counter_state.dart';

class CounterCubit extends Cubit {
  CounterCubit() : super(CounterState(counterValue: 0));

  void increment() => emit(
      CounterState(counterValue: state.counterValue + 1, wasIncremented: true));

  void decrement() => emit(CounterState(
      counterValue: state.counterValue - 1, wasIncremented: false));
}
  

2. Bloc Listener

BlocListener(
      listener: (context, state) {
        if (state is InternetConnected &&
            state.connectionType == ConnectionType.Wifi) {
          context.bloc().increment();
        } else if (state is InternetConnected &&
            state.connectionType == ConnectionType.Mobile) {
          context.bloc().decrement();
        }
      },
      

BuildContext

Notion of BuildContext
Another important notion is the BuildContext.
A BuildContext is nothing else but a reference to the location of a Widget within the tree structure of all the Widgets which are built.
In short, think of a BuildContext as the part of Widgets tree where the Widget is attached to this tree.
A BuildContext only belongs to one widget.
If a widget ‘A’ has children widgets, the BuildContext of widget ‘A’ will become the parent BuildContext of the direct children BuildContexts.
Reading this, it is clear that BuildContexts are chained and are composing a tree of BuildContexts (parent-children relationship).
If we now try to illustrate the notion of BuildContext in the previous diagram, we obtain (still as a very simplified view) where each color represents a BuildContext (except the MyApp one, which is different):

BuildContext visibility (Simplified statement):

‘Something’ is only visible within its own BuildContext or in the BuildContext of its parent(s) BuildContext.

From this statement we can derive that from a child BuildContext, it is easily possible to find an ancestor (= parent) Widget.

An example is, considering the Scaffold > Center > Column > Text:
context.ancestorWidgetOfExactType(Scaffold) => returns the first Scaffold by going up to tree structure from the Text context.

From a parent BuildContext, it is also possible to find a descendant (= child) Widget but it is not advised to do so (we will discuss this later).

Wrong Assumptions about BuildContext



Screenshot-2022-02-05-191054
Screenshot-2022-02-05-191026Screenshot-2022-02-05-191224






Post a Comment

Previous Post Next Post

Subscribe Us


Get tutorials, Flutter news and other exclusive content delivered to your inbox. Join 1000+ growth-oriented Flutter developers subscribed to the newsletter

100% value, 0% spam. Unsubscribe anytime