如何解决Flutter中的null调用了方法'dispose'
我想使应用程序变得扑朔迷离,为了使用focusNode我编写了这段代码->
FocusNode _titleFocus;
FocusNode _descriptionFocus;
FocusNode _todoFocus;
@override
void initState() {
// TODO: implement initState
super.initState();
if(widget.task!=null){
_titleFocus = FocusNode();
_descriptionFocus = FocusNode();
_todoFocus = FocusNode();
}
}
@override
void dispose() {
// TODO: implement dispose
_titleFocus.dispose();
_descriptionFocus.dispose();
_todoFocus.dispose();
super.dispose();
}
我首先在代码下面启动FocusNode,该focusNode在退出待办任务对象时可以正常工作,但是当我想创建一个新对象并将一个焦点传递给另一个焦点时,它将无法正常工作。我用这段代码传递焦点...
focusNode: _titleFocus,_descriptionFocus.requestFocus();
但是它出错了,并显示消息->
The following NoSuchMethodError was thrown while finalizing the widget tree:
The method 'dispose' was called on null.
Receiver: null
Tried calling: dispose()
解决方法
“当我要创建一个新的焦点并将一个焦点传递到另一个焦点时,它将无法正常工作。”
由于您在FocusNode
方法中的情况,initState
无法实例化。因此出现错误(The method 'dispose' was called on null.
)。
要解决此问题,您可以在dispose()
方法的FocusNode
上调用dispose
之前检查条件。
@override
void dispose() {
// TODO: implement dispose
if(widget.task!=null){ // check whether it is an existing todo or a new one before calling dispose
_titleFocus.dispose();
_descriptionFocus.dispose();
_todoFocus.dispose();
}
super.dispose();
}
更新:您可以使用IF
表示的null aware operator
来代替?.
检查:
在下面添加了一个示例:
@override
void dispose() {
// TODO: implement dispose
_titleFocus?.dispose();
_descriptionFocus?.dispose();
_todoFocus?.dispose();
}
super.dispose();
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。