Erik Johansson
Erik Johansson

Reputation: 1248

flutter BlocProvider not recreated when widget tree is reloaded

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?

Upvotes: 3

Views: 839

Answers (2)

Erik Johansson
Erik Johansson

Reputation: 1248

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.

Upvotes: 4

Piyush Dubey
Piyush Dubey

Reputation: 306

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!

Upvotes: 1

Related Questions