Junior — Middle
Can you explain how InheritedWidget works in Flutter?
sobes.tech AI
Answer from AI
InheritedWidget in Flutter is used to pass data down the widget tree without the need to explicitly pass them through the constructors of each child widget. This allows child widgets to access shared data and automatically update when it changes.
Working principle:
- InheritedWidget stores data that should be accessible to descendants.
- Descendants access this data via the
of(context)method. - If the data in InheritedWidget changes, Flutter notifies all widgets that depend on this InheritedWidget, and they rebuild.
Example:
class MyData extends InheritedWidget {
final int counter;
MyData({required this.counter, required Widget child}) : super(child: child);
static MyData? of(BuildContext context) {
return context.dependOnInheritedWidgetOfExactType<MyData>();
}
@override
bool updateShouldNotify(MyData oldWidget) {
return oldWidget.counter != counter;
}
}
// Usage:
// Wrap the widget tree in MyData in the parent widget
// Access data in child widgets via MyData.of(context)?.counter
Thus, InheritedWidget helps efficiently share state and data among widgets without excessive parameter passing.