...

/

State Management with InheritedWidget

State Management with InheritedWidget

Learn to use InheritedWidget to manage the state in your Flutter application.

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.

Press + to interact
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:

Press + to interact
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. ...