Discover how to share data effortlessly in your app and avoid endless manual passing!
Why InheritedWidget concept in Flutter? - Purpose & Use Cases
Imagine you have a big family photo album. Every time someone wants to see a picture, you have to personally hand it over. If the album moves or changes, you must tell everyone again. This is like passing data manually through many layers in your app.
Passing data manually through each screen or widget is slow and tiring. You might forget to pass it somewhere, causing errors. It's like playing a long game of telephone where messages get lost or mixed up.
InheritedWidget acts like a shared family album on a table. Everyone can look at it anytime without asking you. When the album updates, everyone sees the new pictures automatically. This makes sharing data easy and reliable across your app.
class ParentWidget extends StatelessWidget { final String data = 'Hello'; Widget build(BuildContext context) { return ChildWidget(data: data); } } class ChildWidget extends StatelessWidget { final String data; ChildWidget({required this.data}); Widget build(BuildContext context) { return Text(data); } }
class DataProvider extends InheritedWidget { final String data; DataProvider({required this.data, required Widget child}) : super(child: child); static DataProvider? of(BuildContext context) => context.dependOnInheritedWidgetOfExactType<DataProvider>(); @override bool updateShouldNotify(DataProvider old) => data != old.data; } class ChildWidget extends StatelessWidget { Widget build(BuildContext context) { final data = DataProvider.of(context)?.data ?? ''; return Text(data); } }
InheritedWidget lets your app share data easily and update many parts at once without messy code.
Think of a weather app where the current temperature is shown on many screens. Using InheritedWidget, when the temperature updates, all screens show the new value instantly without extra work.
Passing data manually is slow and error-prone.
InheritedWidget shares data efficiently across widgets.
It updates all listening widgets automatically when data changes.