Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dependOnInheritedWidgetOfExactType() returns null

Tags:

flutter

dart

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.

like image 915
0xCAF2 Avatar asked Dec 19 '19 06:12

0xCAF2


1 Answers

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.

like image 178
Rémi Rousselet Avatar answered Oct 25 '22 20:10

Rémi Rousselet