InheritedWidget is a special type of widget that can efficiently propagate information down the widget tree. This allows widgets to access shared data without having to pass the data explicitly down the tree. The primary use case for InheritedWidget is for efficient data propagation and to avoid unnecessary widget rebuilds.
class Theme extends InheritedWidget {
final ThemeData data;
Theme({
Key? key,
required this.data,
required Widget child,
}) : super(key: key, child: child);
bool updateShouldNotify(Theme oldWidget) {
return data != oldWidget.data;
}
static ThemeData of(BuildContext context) {
return context.dependOnInheritedWidgetOfExactType<Theme>()!.data;
}
}
void main() => runApp(App());
class App extends StatelessWidget {
Widget build(BuildContext context) {
return Theme(
data: ThemeData(
primaryColor: Colors.blue,
// other theme data...
),
child: HomePage(),
);
}
}
class HomePage extends StatelessWidget {
Widget build(BuildContext context) {
ThemeData themeData = Theme.of(context);
return MaterialApp(
theme: themeData,
home: Scaffold(
appBar: AppBar(
title: Text('InheritedWidget Example'),
),
body: Center(child: Text('Hello World')),
),
);
}
}
ChangeNotifier is a class in Flutter (specifically in the foundation library) that provides an implementation of the Listenable interface. It's commonly used in conjunction with the Provider package for state management purposes.
class CounterModel extends ChangeNotifier {
int _count = 0;
int get count => _count;
void increment() {
_count++;
notifyListeners();
}
}
void main() => runApp(App());
class App extends StatelessWidget {
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (context) => CounterModel(),
child: Home(),
);
}
}
class Home extends StatelessWidget {
Widget build(BuildContext context) {
// Get the CounterModel
var counterModel = Provider.of<CounterModel>(context);
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text('ChangeNotifier Example')),
body: Center(
child: Text('Count: ${counterModel.count}'),
),
floatingActionButton: FloatingActionButton(
onPressed: counterModel.increment,
child: Icon(Icons.add),
),
),
);
}
}
ValueNotifier is a simple utility class in Flutter that extends ChangeNotifier. It holds a single value and notifies its listeners when that value changes. This makes it a handy tool for state management for simple cases, especially when you want to rebuild specific widgets in response to changes in a value.
A wrapper around InheritedWidget to make them easier to use and more reusable.
By using provider instead of manually writing InheritedWidget, you get:
flutter pub add provider