State Management with InheritedWidget
Explore how to manage state in Flutter applications using InheritedWidget. Learn to extend InheritedWidget, create a state class, and access shared state across widgets. This lesson guides you through updating the UI dynamically as you add, update, or delete tasks, helping you build scalable Flutter apps with efficient state sharing.
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:
The code snippet above defines the data accessible throughout our widget tree and overrides the updateShouldNotify class, which determines whether Flutter should redraw widgets.