Search⌘ K
AI Features

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.

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.

Using InheritedWidget to manage application state
Using InheritedWidget to manage application state

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());
}
State management with InheritedWidget—initial code

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:

Dart
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);
@override
bool 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.

Creating a state

...