首页 > 解决方案 > dependOnInheritedWidgetOfExactType() 返回 null

问题描述

我试图将我的财产寄给InheritedWidget它的孩子。

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;
  }
}

我提到这里。小部件由以下人员创建:

Detector(
  isEditable: otherObj.isEditable,
  child: command.makeWidget(context) // Extension method that returns new widget
);

并且makeWidget()方法调用of方法:

   final detector = Detector.of(context);
    if (detector != null && detector.isEditable) {
      return Container(
        child: ...,
      );
    }

总是返回 null。为什么dependOnInheritedWidgetOfExactType()返回null?我使用扩展方法,但给它来自祖先小部件的上下文。

标签: flutterdart

解决方案


这就是您不应该使用函数而不是类来制作可重用小部件的原因之一。创建小部件的函数和类有什么区别?

您正在调用dependOnInheritedWidgetOfExactType<Detector>BuildContext祖先Detector

代替:

Detector(
  isEditable: otherObj.isEditable,
  child: command.makeWidget(context) // Extension method that returns new widget
);

重构command.makeWidget(context),使其成为一个StatelessWidget类而不是一个函数。

这将为您提供BuildContext一个后代,Detector并将解决您的问题。


推荐阅读