flutter bloc best practices by blocs

236

I think a good way is having a bloc for each feature, and one repository or storage.

I usually make navigation by passing object's unique id to widget's constructor and then opening modal page with its own bloc, that handles loading description etc.

For example I need to load a list of products. I wrap my main product screen with RepositoryProvider, which provides Product repository. Repository contains all logic i need (fetching, sorting, taking one item from item list with unique id, etc.)

Then, I wrap my page with bloc provider, and pass my repo by constructor, so now bloc whould have access to my repository. Bloc only manages repo to ui connection. In my list of item i pass item's id, so if i tap on item, i can pass its id to another bloc, that does different logic (for example, opening modal page with description)

Share:
236
Rodrigue
Author by

Rodrigue

Updated on December 27, 2022

Comments

  • Rodrigue
    Rodrigue over 1 year

    I currently create a prototype project which implements a lot of features like navigation management, errors management, storage management etc etc

    I'm facing now a question with blocs. I want to know which is the best practices using blocs, in fact, imagine I have a product system like list of products, product detail, select product.

    Does I need to have only one bloc which can take 3 events like

    1. Get List Products
    2. Get Product Id
    3. Select Product

    with differents states like GetListInitial, GetProductInitial, SelectProductInitial and others for "loaded", "finished" for example

    And then in my 2 pages I can use a BlocConsumer which listen, in the listProduct page GetListInitial, GetListFinished and the product Detail page GetProductInitial, GetProductFinished ? I can also use 2 BlocConsumer in the same page which are listening differents states for example listing products and then select one.

    Or

    Does I need to have three differents blocs which can take 1 event and do the same process with each bloc.

    We can consider that the 1st solution can group events by features but in fact does not respect what Flutter want like works with widget because in my example 3 BlocConsumer will be handle if one event occured, but only 1 will do things.

    But in the 2nd solution, it means that if I got a huge application so I will have a very very lot of blocs, right ? Which is the best solution?

    Thanks