flutter BlocProvider not recreated when widget tree is reloaded

632 views Asked by At

I'm using Flutter Bloc (https://bloclibrary.dev) in my app but I'm having trouble with reinitializing a bloc provider when the widget tree is reloaded.

A simplified version of the tree structure in my app looks like this

[BlocProviderA]
  -> [BlocBuilderA]
    -> [PageView] // this shouldn't really matter but showing it here anyway in case it does :) 
      -> [BlocProviderB]
        -> [BlocBuilderB]

Under certain conditions, BlocA's state will change so that BlocBuilderA will rebuild and return a new child (PageView), the same tree structure but with some new data. However, BlocProviderB is never recreated (BlocProvider.create is never called) when the widget tree i replaced by BlocBuilderA. BlocBuilderB is called though.

Can anyone shed some light to why this is happening? Is the old widget tree simply reused and this is why BlocProvider.create is never called for the BlocProviderB?

2

There are 2 answers

2
Piyush Dubey On

There are 2 usage of how you want to include BLoC in your project.

  • First you have a single component with multiple events
  • Second you have a widget tree and you want to pass your bloc in between

You need to create a instance in init of a widget for both of them and use it directly in parent and pass it on in build method for child component.

Add a more detail in reply if you haven't found your answer yet!

0
Erik Johansson On

Seems as the element is reused if the key and widgets are equal in the new subtree. I managed to "force" a recreation of the subtree by assigning a new key to the PageView.