简体   繁体   中英

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?

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.

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM