In Flutter, an InheritedWidget is a special type of widget that allows data to be passed down through the widget tree to its descendants. It's particularly useful when you have data that needs to be accessible by multiple widgets in your app, without the need to pass the data explicitly to each widget.
Attributes:
InheritedWidget doesn't have any specific attributes of its own. Instead, it provides a way to access data through its ancestor widgets using the of
method.
Example:
Here's a basic example demonstrating the usage of an InheritedWidget:
import 'package:flutter/material.dart';
// Define a custom InheritedWidget
class MyInheritedWidget extends InheritedWidget {
// Data to be shared across the widget tree
final String data;
MyInheritedWidget({required this.data, required Widget child})
: super(child: child);
// Method to access the nearest instance of MyInheritedWidget from a descendant
static MyInheritedWidget of(BuildContext context) {
return context.dependOnInheritedWidgetOfExactType<MyInheritedWidget>()!;
}
@override
bool updateShouldNotify(MyInheritedWidget oldWidget) {
// Always return true to trigger rebuilds when the data changes
return true;
}
}
// Widget using MyInheritedWidget
class MyWidgetUsingInheritedWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
// Access the data provided by MyInheritedWidget
final inheritedData = MyInheritedWidget.of(context).data;
return Container(
alignment: Alignment.center,
child: Text(
inheritedData,
style: TextStyle(fontSize: 18),
),
);
}
}
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('InheritedWidget Example'),
),
body: MyInheritedWidget(
data: 'Hello, InheritedWidget!',
child: MyWidgetUsingInheritedWidget(),
),
),
);
}
}
In this example:
We define a custom InheritedWidget named MyInheritedWidget, which contains a piece of data (data).
The MyInheritedWidget class provides a method named of, which allows descendants to access the nearest instance of MyInheritedWidget from the widget tree.
We create a widget named MyWidgetUsingInheritedWidget, which uses the MyInheritedWidget to access the data.
In the MyApp widget tree, we wrap MyWidgetUsingInheritedWidget with MyInheritedWidget. This allows MyWidgetUsingInheritedWidget to access the data provided by MyInheritedWidget.
When the data in MyInheritedWidget changes, it automatically triggers a rebuild of MyWidgetUsingInheritedWidget and its descendants, ensuring that the UI is always up-to-date with the latest data.