Junior — Middle
Explain the main differences between StatefulWidget, StatelessWidget, and InheritedWidget in Flutter.
sobes.tech AI
Answer from AI
StatelessWidget is a widget without state. It is built once and does not change its appearance unless the input parameters change. It is used for displaying static UI.
StatefulWidget is a widget with state. It can change its appearance in response to events or data changes. For this, a separate State object is created, which manages the state and triggers a redraw.
InheritedWidget is a special widget that allows passing data down the widget tree without explicitly passing it through constructors. It is used to implement global state or shared data that child widgets can access.
Example of using InheritedWidget to pass a theme:
class MyTheme extends InheritedWidget {
final Color color;
MyTheme({required this.color, required Widget child}) : super(child: child);
static MyTheme? of(BuildContext context) {
return context.dependOnInheritedWidgetOfExactType<MyTheme>();
}
@override
bool updateShouldNotify(MyTheme oldWidget) => color != oldWidget.color;
}
In summary:
- StatelessWidget — without state
- StatefulWidget — with state
- InheritedWidget — for passing data down the widget tree