State Management with InheritedWidget
Learn to use InheritedWidget to manage the state in your Flutter application.
We'll cover the following...
As our app gets bigger, our Flutter widget tree gets deeper. Passing data within the widget tree gets more confusing and trickier.
InheritedWidget
is a Flutter widget that allows the state to be shared down the widget tree. It defines the state at the root of a tree or subtree that can be accessed by all children using the context
object.
In this lesson, we’ll update the state of the app below using InheritedWidget
:
import 'package:flutter/material.dart'; import 'presentation/my_app.dart'; void main() { runApp(const MyApp()); }
Using InheritedWidget
Now that we have an overview of how state management works with InheritedWidget
, let’s learn how to use it by practicing.
Extending InheritedWidget
To use InheritedWidget
, we have to extend it in oour class. Add the code snippet given below in the lib/utils/inherited_tasks.dart
file:
import 'package:flutter/material.dart';import 'tasks_state.dart';class InheritedTasksWidget extends InheritedWidget {final TasksStateWidgetState state;const InheritedTasksWidget({Key? key,required this.state,required Widget child,}) : super(key: key, child: child);@overridebool updateShouldNotify(covariant InheritedTasksWidget oldWidget) => true;}
The code snippet above defines the data accessible throughout our widget tree and overrides the updateShouldNotify
class, which determines whether Flutter should redraw widgets. ...