Search code examples
flutterdartblocrxdart

How to persist bloc instance in widget tree


I'm using an InheritedWidget to expose a bloc class to child components. However, every time the widget tree gets recreated, a new instance of the bloc class is instantiated. As I'm using BehaviourSubject classes to store the latest values of some textfields, I'm loosing the current values with every recreation. How could this be solved, i.e. the bloc class should only be instantiated once.


Solution

  • It depends on how your provider were made, if it's an a extension of StatefulWidget with an a InheritedWidget.

    If it's only extends from a InheritedWigdet, you'll miss the dispose method because it doesn't extends from StatefulBuilder, but, will never instantiate again, and the dispose method will be when you'll close your application. Check this example:

    class Provider extends InheritedWidget {
      Provider({Key key, Widget child}) : super(key: key, child: child);
    
      final AppBloc bloc = AppBloc();
    
      static AppBloc of(BuildContext context) =>
          (context.inheritFromWidgetOfExactType(Provider) as Provider).bloc;
    
      @override
      bool updateShouldNotify(Provider oldWidget) => true;
    }
    

    This AppBloc is a component that has all my applcation's blocs.

    But, if your provider extends an a StatefulWidget with a InheritedWidget, you can pass your bloc as a constructor parameter in the class you want, and this class should be Stateful too, so you can pass in the initState and will be rebuilted only when you access it again.