State Management with Flutter BLoc Pattern - Expert
byLokesh Jangid•
0
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 {}
part of 'counter_cubit.dart';
class CounterState {
int counterValue;
bool wasIncremented;
CounterState({
@required this.counterValue,
this.wasIncremented,
});
}
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).
Get tutorials, Flutter news and other exclusive content delivered to your inbox. Join 1000+ growth-oriented Flutter developers subscribed to the newsletter