Flutter 104 Introduction to BLOC
A component that converts incoming Events (Streams) to outgoing States (Streams).
Events - Inputs to a bloc e.g. in response of user interaction
States - Outputs of a bloc and is part of application state. Notified system to redraw UI with build()
Transition - Change of state, consist of current, transition and next state
Why Stream?
Stream - "container" for asynchronous data
Future (computation that is not completed immediately) Vs Stream (sequence/iterable, instead of asking for it, will inform you of event that is ready)
Receive by: await for (hint hint for loop)
Streams:
Single Subscription stream - listened once
Broadcast Stream - more than one listener can listen at the same time and it can be listened again
Methods that:
Process stream and return a result,
Modify by returning a new stream based on original,
Transform and
Listen which return StreamSubscription that allows you to pause, resume and cancel subscription.
How to implement Blocs?
extend Bloc class,
implement mapEventToState () - accept event argument and return Stream of new States. Has currentState property
Packages
bloc - implemented/extended to invoke mapEventToState
flutter_bloc - to replace StreamBuilder (BlocBuilder, BlocProvider and BlocListener).
BlocBuilder - return widget based on bloc's state
BlocProvider - provide Bloc to its children (Use BlocProviderTree for multiple BlocProvider)
BlocListener - invoke listener for state changes in Bloc
Useful Methods in Library
Bloc Class:
currentState() - return Current State of the Bloc
dispatch() - takes event and trigger mapEventToState
mapEventToState - take event, return State as Stream
Cross sharing of State
Example 1: Wrap in MaterialApp with BlocProvider like:
BlocProvider(bloc: bloc1, child: MaterialApp(...));
Access bloc1 from anywhere using:
BlocProvider.of<Bloc1>(context)
Example 2: Pizza
https://stackoverflow.com/questions/54523971/flutter-bloc-being-recreated
Example 3:
https://stackoverflow.com/questions/53918475/flutter-bloc-pattern-update-bloc-streams-based-another-blocs-stream
Comments
Post a Comment