Flutter : same BlocBuilder on two consecutive pages

296

Solution 1

First solution: see w461 answer.

Second solution: in my case, I think it is better to create new states for each page.

Solution 2

Create a new instance of that bloc for the 2nd page

Share:
296
Gabriel Curinga
Author by

Gabriel Curinga

Updated on December 26, 2022

Comments

  • Gabriel Curinga
    Gabriel Curinga over 1 year

    I'm working on an application and we decided to use the BLoC pattern. I am facing a recurrent problem in my application. Indeed, I created a bloc called CatalogBloc.

    On my first page, there is a widget that uses the following BlocBuilder:

    ...
    BlocBuilder<CatalogBloc, CatalogState>(
                buildWhen: (previous, current) {
                  return current is CatalogArticlesLoadIsFinished ||
                      current is CatalogArticlesLoadInProgress;
                },
                builder: (context, state) {
                  return CatalogArticlesWidget(
                    data: state.data,
                  );
                },
              );
    ...
    

    From this page, I can navigate to a page that contains this same BlocBuilder and same widget (CatalogArticlesWidget). This second page calls the bloc CatalogBloc to reload data of the same type, but filtered in initState:

    @override
    void initState() {
      context.read<CatalogBloc>().add(CatalogArticlesLoadRequested(family: widget.family));
      super.initState();
    }
    

    So when I pop to the first screen (from the second), the data has changed.

    What is the cleanest way to avoid this kind of behavior ?