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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...