I tried to send the property of my InheritedWidget
to its child.
class Detector extends InheritedWidget {
final bool isEditable;
Detector({@required this.isEditable, @required Widget child, Key key})
: super(child: child, key: key);
static Detector of(BuildContext context) {
return context.dependOnInheritedWidgetOfExactType<Detector>();
}
@override
bool updateShouldNotify(Detector oldWidget) {
return oldWidget.isEditable != isEditable;
}
}
I referred here. The widget is created by:
Detector(
isEditable: otherObj.isEditable,
child: command.makeWidget(context) // Extension method that returns new widget
);
And makeWidget()
method calls the of
method:
final detector = Detector.of(context);
if (detector != null && detector.isEditable) {
return Container(
child: ...,
);
}
always returns null.
Why does dependOnInheritedWidgetOfExactType()
return null? I use the extension method but give it the context from an ancestor widget.
That's one of the reasons you shouldn't use functions instead of classes to make reusable widgets. What is the difference between functions and classes to create widgets?
You are calling dependOnInheritedWidgetOfExactType<Detector>
on a BuildContext
that is an ancestor of Detector
.
Instead of:
Detector(
isEditable: otherObj.isEditable,
child: command.makeWidget(context) // Extension method that returns new widget
);
refactor command.makeWidget(context)
such that it's a StatelessWidget
class instead of a function.
That will give you a BuildContext
that is a descendant of Detector
and will fix your issue.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With