问题描述
我想使应用程序变得扑朔迷离,为了使用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();
}