What is InheritedWidget in Flutter: Explanation and Example
InheritedWidget is a special widget that allows data to be efficiently shared down the widget tree to its descendants. It helps widgets access shared information without passing it through constructors manually.How It Works
InheritedWidget works like a shared message board in a family house. Imagine you have a note on the fridge that everyone in the house can read. Instead of telling each person individually, you put the message in one place. Similarly, InheritedWidget holds data that child widgets can read anytime.
When the data inside the InheritedWidget changes, Flutter automatically notifies the widgets that depend on it to rebuild and update their display. This makes data sharing efficient and keeps the UI in sync without extra wiring.
Example
This example shows a simple InheritedWidget that shares a counter value with its child widget. The child reads the counter and displays it.
import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class CounterProvider extends InheritedWidget { final int counter; const CounterProvider({Key? key, required this.counter, required Widget child}) : super(key: key, child: child); static CounterProvider? of(BuildContext context) { return context.dependOnInheritedWidgetOfExactType<CounterProvider>(); } @override bool updateShouldNotify(CounterProvider oldWidget) { return oldWidget.counter != counter; } } class MyApp extends StatefulWidget { @override State<MyApp> createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { int _counter = 0; void _increment() { setState(() { _counter++; }); } @override Widget build(BuildContext context) { return CounterProvider( counter: _counter, child: MaterialApp( home: Scaffold( appBar: AppBar(title: const Text('InheritedWidget Example')), body: Center(child: CounterText()), floatingActionButton: FloatingActionButton( onPressed: _increment, child: const Icon(Icons.add), ), ), ), ); } } class CounterText extends StatelessWidget { @override Widget build(BuildContext context) { final counter = CounterProvider.of(context)?.counter ?? 0; return Text('Counter value: $counter', style: const TextStyle(fontSize: 24)); } }
When to Use
Use InheritedWidget when you want to share data or state efficiently across many widgets without passing it down manually through constructors. It is useful for global app settings, themes, or user login info.
For example, if you have a theme color or user preferences that many widgets need, InheritedWidget lets you provide that data once and access it anywhere below in the widget tree.
Key Points
- InheritedWidget shares data down the widget tree efficiently.
- Widgets that use the data rebuild automatically when it changes.
- It avoids passing data through many widget constructors.
- Commonly used for app-wide data like themes or user info.