flutter - 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?我使用扩展方法,但给它来自祖先小部件的上下文。
解决方案
这就是您不应该使用函数而不是类来制作可重用小部件的原因之一。创建小部件的函数和类有什么区别?
您正在调用dependOnInheritedWidgetOfExactType<Detector>
的BuildContext
祖先Detector
。
代替:
Detector(
isEditable: otherObj.isEditable,
child: command.makeWidget(context) // Extension method that returns new widget
);
重构command.makeWidget(context)
,使其成为一个StatelessWidget
类而不是一个函数。
这将为您提供BuildContext
一个后代,Detector
并将解决您的问题。
推荐阅读
- azure-cognitive-services - 表单识别器中的不同表单模板
- azure - Azure VM 出现预配失败问题
- excel - 将鼠标悬停在 Excel 应用程序上时出现隐藏的用户窗体
- maven - 如何在 Pom.xml 中为 Firefox 和 Internet Explorer 添加 maven 依赖项?
- html - 如何减少压痕
- UILabel html属性文本中的标签?
- javascript - how to pass value from input field to form action url as parameter on type
- php - 回显后从文件中删除行(或满足其他条件)
- laravel - Laravel错误紧凑():未定义的变量
- c++ - 在具有 2 个模板的模板类中重载 operator+
- spring-boot - 如何在springboot 2.0.1中用方括号覆盖属性