SoFunction
Updated on 2025-04-06

flutter Bloc implementation principle example analysis

Preface

existflutterIn development, we useblocFramework, responsive development based on state changes. In this article, Xiaobo GeneralblocThe core business block is disassembled and simplified. Let’s talk about its implementation ideas. The core capabilities of bloc are divided into the following two points:

  • Add Eventevent, convert 'event stream' to 'state stream'state
  • monitorblocStream, every timestateStatus change, notificationwidgetrenew

Next, use the custom Bloc method to explain the principles and structure of Bloc to you.

1. Event Flow > Status Flow (Transfer)

First, we willblocCode simplification, let's take a lookblocHow to convert an event stream to a state stream. The simplified code is as follows:

import 'dart:async';
abstract class ACubit<State> {
  StreamController<State> _controller = StreamController<State>.broadcast();
  State _state;
  State get state => _state;
  ACubit(this._state);
  ///Send State status into the stream  void emit(State state) {
    if (_controller.isClosed) return;
    if (state == _state) return;
    _state = state;
    _controller.add(_state);
  }
  ///Providing method external listening State  StreamSubscription<State> listen(
    void Function(State state) onData, {
    Function onError,
    void Function() onDone,
    bool cancelOnError,
  }) {
    return _controller.(
      onData,
      onError: onError,
      onDone: onDone,
      cancelOnError: cancelOnError,
    );
  }
  Future<void> close() {
    return _controller.close();
  }
}

ACubitProvide the most basic capabilities. supplylistenMethod to external monitor 'State' changes;emitMethods are used to respondstateStatus change.

abstract class ABloc<Event, State> extends ACubit<State> {
  final _eventController = StreamController<Event>.broadcast();
  ABloc(State initState) : super(initState) {
    _bindEventToState();
  }
  ///Send event  void add(Event event) {
    if (_eventController.isClosed) return;
    _eventController.add(event);
  }
  /// Need to implement the upper layer (convert to state according to event)  Stream<State> mapEventToState(Event event);
  ///Convert event stream to state stream  _bindEventToState() {
    _eventController.stream
        // asyncExpand type converts the stream content, but the result is still a stream        .asyncExpand((event) => mapEventToState(event))
        .listen((nextState) {
      ///Compare nextState with the current state, put it into the stream after the comparison is successful      emit(nextState);
    });
  }
}

ABlocIt is the base class we use directly. Called in the constructor_bindEventToStateConverts the event stream to a state stream.

2. How to use BlocBuilder to listen for status changes in real time?

Xiao Hong gave a simplified version of the principle explanation:

import 'package:flutter/';
import 'a_bloc.dart';
class BlocBuilder<T extends ACubit<S>, S> extends StatefulWidget {
  final T cubit;
  final Widget Function(BuildContext context, S state) builder;
  const BlocBuilder({
    Key key,
    @required ,
    @required ,
  }) : super(key: key);
  @override
  _BlocBuilderState<S> createState() => _BlocBuilderState<S>();
}
class _BlocBuilderState<S> extends State<BlocBuilder> {
  void _update() {
    setState(() {});
  }
  @override
  void initState() {
    /// Listen to state status changes    ?.listen((_) {
      _update();
    });
    ();
  }
  @override
  void dispose() {
    ?.close();
    ();
  }
  @override
  Widget build(BuildContext context){
    return (
      context,
      ,
    );
  }
}

Encapsulation BlocBuilder

  • Passing a custom bloc into the constructor (inheritance)ABloc),builderPass the argument to obtain each timestateChange notice.
  • existinitStateInitialization methodcubitPerform status monitoring, call directly for each state changesetStateMethod for page update

The call example is as follows:

return BlocBuilder<CountBloc, CountState>(
      cubit: CountBloc(CountState(1)),
      builder: (context, state) {
       return Container(...Omit business code)
      },
    )

Summarize

blocReferenced in the libraryproviderWait for the three-party library. based onInheritedWidgetRealize data sharing capabilities. In this article, Xiao Hong only demonstrates the core processing ideas of Bloc. For details, please refer to the Bloc source code.

Extended

InheritedProvider implements data sharing Bloc adds the problem only once twice at the same time

The above is the detailed content of the analysis of the flutter Bloc implementation principle example. For more information about the flutter Bloc implementation principle, please pay attention to my other related articles!