0
0
Fluttermobile~3 mins

Why InheritedWidget concept in Flutter? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how to share data effortlessly in your app and avoid endless manual passing!

The Scenario

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.

The Problem

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.

The Solution

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.

Before vs After
Before
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);
  }
}
After
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);
  }
}
What It Enables

InheritedWidget lets your app share data easily and update many parts at once without messy code.

Real Life Example

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.

Key Takeaways

Passing data manually is slow and error-prone.

InheritedWidget shares data efficiently across widgets.

It updates all listening widgets automatically when data changes.