Here is an introduction to the principle of BLoC in Flutter and its application scenario. If you are interested, please read this article patiently. I believe you can still gain something ~ ^_^


BLoC before introducing BLoC, let’s introduce some related categories and concepts:

Summary of premise

Stream flow type

  1. Single-subscription streams: There can be only one subscriber
  2. Multiple subscription streams: You can have multiple subscribers and messages will not be received until you subscribe

Single feed -> Multiple feeds: stream.asbroadcaststream ()

StreamBuilder API

Use Stream to construct the UI, as described in the video in the documentation.

How StreamController is used

Here’s how the StreamController works

The input value from sink.add corresponds to the output stream, and the corresponding stream transformation can be made, and then the corresponding place listening to the stream will receive data.

RxDart

For writing asynchronous and event-based programs using observable sequences, refer to RxDart

Enhanced version StreamController:

  1. PublishSubjectStreamcontroll of normal broadcast, listen multiple times (default asynchronous)
  2. BehaviorSubject: a broadcast flow controller that caches the latest event
  3. ReplaySubject: broadcast stream controller that caches multiple data, upper limit can be set

Each xxSubject can be viewed as a unit (reserve below) :

Observable: an Observable that extends Stream, combining Streams and StreamTransformers (default single subscription)

InheritedWidget

Here’s how InheritedWidget works:

Static T of(BuildContext context) => context.inheritFromWidgetOfExactType(T); final t = T.of(context)

How do I use the one above? In the Child component:

Root root = Root.of(context);// Get the Root object
root.data... // Use variables of the root object, etc
Copy the code

Let’s cut to the chase:

State Management: BLoC: Business Logic Component

BLoC is a typical observer pattern

To implement this design pattern with Flutter, use:

  1. BlocProvider Component: InheritedWidget inherits the component + Bloc object
  2. Bloc class: Stream (DART)/Subject(rxdart Stream)

BlocProvider

Several usages of BLoC class and corresponding usage scenarios

Type1: basic initialization and use

Type2: Event conversion State:

Event->State (State transition diagram)

This is done by sending an event through a normal broadcast PublishSubject to an intermediate listener handler: EventHandler performs asynchronous processing according to the obtained event. After processing, some states are converted and returned, and all the returned results are added to the BehaviorSubject. Due to the BehaviorSubject’s characteristics, Pass and retain the latest result. The UI listens to the corresponding state and then makes different interfaces accordingly.

For example: a common scenario for loading data

Here are some handwritten codes from Bloc for logical reference only:

  Stream<AbstractState> eventHandler(AbstractEvent event) async* {
      if (event is InitEvent) {
          yield LoadingState();
          final remoteData = await Request.fetchData();
          yield ResultData(remoteData);
      } else if (event is RefreshState) {
          final remoteData = await Request.fetchData();
          yieldUpdateData(remoteData); }}Copy the code
Type3: registration and login verification

PS: Mixin has added two functions for bloc class. According to the input stream, it can verify whether the mailbox and password meet the requirements

Type4: Shopping list implementation

In the figure above, there is a shopping cart list page pageBloc and the item itemBloc in the shopping cart. The event flows to pageBloc, and monitors the red dot data of pageBloc change for corresponding changes. Meanwhile, monitors the itemBloc of pageBloc to determine whether the corresponding bool value is returned in the shopping cart, indicating whether the state of the corresponding item is updated at the end of the shopping cart and becomes +-.

Specific code reference: ShopItemBloc


Conclusion: The above four scenes are summarized from a foreign famous article. The article is quite long, and it may be tiring to read. If I read it in combination with my summary, I believe it can be quickly understood.

Flutter_bloc is also written by this great god, which can basically meet the usual business needs.

In addition, the latest BlocProviders are implemented based on providers.


If you have any questions, please point out