Flutter : same BlocBuilder on two consecutive pages

Issue

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 ?

Solution

First solution: see w461 answer.

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

Answered By – Gabriel Curinga

Answer Checked By – Willingham (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.