Search code examples
flutterdifferenceconcept

What is the difference of using generic BLoC provider and Inherited widget?


What is the difference of using generic BLoC provider and Inherited widget? Are they the same, do the same, or are they completely different?

I understand that both serve to access a data regardless of the level you are in the widget tree But I would be very pleased if you explained the difference


Solution

  • They serve a similar purpose (deliver state to widgets further down the widget tree), but there are differences in how to retrieve values and how to apply changes.

    In BLoC, you build widgets depending on the current BlocState by using BlocBuilder<MyBloc, MyBlocState> and you add events to the BlocProvider.of<MyBloc>(context) in order to change that value.

    With InheritedWidgets, you can get the current state by context.inheritFromWidgetOfExactType(MyInheritedWidget). But InheritedWidgets are immutable (fields are marked final). You can only change the state, by rebuilding the entire widget. Thats why InheritedWidget is mostly used for things, that rarely change: Theme, MediaQuery, Localization, etc.