mwb 2.0.0 mwb: ^2.0.0 copied to clipboard
Flutter package for the Model-Widget-BLoC pattern
Flutter package for the Model-Widget-BLoC (MWB) pattern.
This project contains a small set of classes and a sample project to demonstrate the MWB pattern, which is inspired by the Reactive Programming - Streams - BLoC article.
The actual library code is fairly small and only contains a few classes. The reason for this is that the MWB pattern shown in this repository is trying to keep things small and simple, but rich on possibilities to extend while being less dependant on libraries that dictate structure.
For further explanation of the pattern read the README of the sample projects
General structure #
The idea is the same as with other state-management patterns: Separate the "responsability & ownership" for logic & data from UI classes.
- Widget: Plain UI, straightforward Widgets that display something
- BLoC: Business Logic Component. An abstract object that contains cached data/state and can execute business logic. This is where the access to the model classes happens.
- Model: Anything that can act as a data source. That can be a DAO, or a class directing to REST endpoints or similar.
Library contents #
The library itself contains 3 classes: BlocProvider, BaseBloc, Instantiable.
Instantiables are objects with a lifecycle, similar to the one of a widget State. So every time you need an initialization and a destruction process you can implement this class.
BaseBlocs are derived from Instantiables. Their primary purpose is to mark classes explicitly as a Bloc which are used by the BlocProvider.
BlocProviders are widgets that are used to hold the instance of a bloc, manage it's lifecycle and provide that instance down the widget tree.
Bloc access #
In order to create a Bloc for a "widget tree scope" you'll have to wrap that widget inside a
BlocProvider( bloc: MyPageBloc(), child: MyPage(), );
You can then access the bloc instance by calling
_bloc = BlocProvider.of(context);
inside your widget/state (usually in
initState). Casting is performed automatically.