In this project, I have developed a flutter app which implements bloc architecture to build an infinite scrollable list which loads data from REST API, jsonPlaceholder.
It followed following steps:
- Data Repository: @TODO need to move from BLoC.
- Model: Create
post.dart
model.- This is simple PODO class with constructor and getter.
- uses equatable to compare two objects.
- Events: Fetched;
- Create abstract class, extend Equatable
- Create class for each of these events by extending abstract class.
- States: Loading, Loaded, Error.
- Create abstract class, extend Equatable
- Create class for each of these events by extending abstract class.
- Define variables to be affected in each State.
- No logic here, only scaffolds, factories.
- Bloc: A class which maps events and states classes.
- Provides initial state
- mapEventsToState
- Also, fetch posts using HTTP Client, this needs to be moved to repository, Step 0.
- Added,
debouce events
by transforming state before mapping, Overriding transform allows us to transform the Stream before mapEventToState is called. This allows for operations like distinct(), debounceTime(), etc... to be applied. Uses rxdart library.
- UI: Then main class:
main()
function calls theApp()
class.- In
App()
widget, we useBlocProvider
, provides instance ofPostBloc
to subtree. - In
child: HomePage()
, we useBlocBuilder
to return widget which updates on state change. - Add
fetched
event to bloc. Whenever the user scrolls, we calculate how far away from the bottom of the page they are and if the distance is โค our _scrollThreshold we add a Fetch event in order to load more posts.
- Enhancements: We made app more robust by adding:
- Logging: We deligated bloc
transitions
by creating our ownBlogDeligate
. This logs all state transition with { current state, the event, and the next state } data. - Optimization: We debounced the events. Overriding
transform
allows us to transform the Stream before mapEventToState is called. Using this we adddebounceTime
toevents
. This prevents spamming of API. 500ms is minimum time between each call.
- Logging: We deligated bloc
Screenshots:
![]() |
![]() |
---|---|
Initial State | All posts loaded |
App Structure:
- lib
- bloc
- post_bloc.dart
- post_event.dart
- post_state.dart
- simple_bloc_deligate.dart
- models
- post.dart
- main.dart
- bloc
This project was based on Bloc tutorial by @felangel.
Thank you!