Inherited Widgets: Application

Learn about inherited widgets and build an actual state management application with them.

Separating inherited widgets

We will separate our inherited widgets in a separate folder. Let us break down our app structure a little bit.

Inside our lib folder, the folder structure looks like the following:

controller/inherited-widget/widgets-lists/widgets_lists.dart

Now the widget lists include these two inherited widgets.

Press + to interact
import 'package:flutter/material.dart';
class EyeColor extends InheritedWidget {
const EyeColor({
Key? key,
@required this.color,
required Widget child,
}) : assert(color != null),
super(key: key, child: child);
final Color? color;
static EyeColor? of(BuildContext context) {
return context.dependOnInheritedWidgetOfExactType<EyeColor>();
}
@override
bool updateShouldNotify(EyeColor old) => color != old.color;
}
class ChangingAge extends InheritedWidget {
const ChangingAge({
Key? key,
@required this.age,
required Widget child,
}) : assert(age != null),
super(key: key, child: child);
final ChangeAge? age;
static ChangingAge? of(BuildContext context) {
return context.dependOnInheritedWidgetOfExactType<ChangingAge>();
}
@override
bool updateShouldNotify(ChangingAge old) => age != old.age;
}
class ChangeAge {
int age;
ChangeAge({this.age: 55});
void changeAge() {
age += 5;
}
}

Why does scope matter in passing context?

We should remember that many widgets do not consume the same context in the widget tree. This means there could be widgets that may not exist in the scope. The value that context carries on its ...

Get hands-on with 1400+ tech skills courses.