Preface
existflutter
In development, we useblocFramework, responsive development based on state changes. In this article, Xiaobo Generalbloc
The 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 Event
event
, convert 'event stream' to 'state stream'state
- monitor
bloc
Stream, every timestate
Status change, notificationwidget
renew
Next, use the custom Bloc method to explain the principles and structure of Bloc to you.
1. Event Flow > Status Flow (Transfer)
First, we willbloc
Code simplification, let's take a lookbloc
How 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(); } }
ACubit
Provide the most basic capabilities. supplylisten
Method to external monitor 'State' changes;emit
Methods are used to respondstate
Status 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); }); } }
ABloc
It is the base class we use directly. Called in the constructor_bindEventToState
Converts 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
),builder
Pass the argument to obtain each timestate
Change notice. - exist
initState
Initialization methodcubit
Perform status monitoring, call directly for each state changesetState
Method 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 onInheritedWidget
Realize 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!