Reputation: 61
I want to make to do app in flutter, for use of focusNode i write this code ->
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();
}
I initiate the FocusNode first below the code, this focusNode work correctly in exiting todo task object but when i want to create new one and passing focus one to another it's not working. I use this code for passing focus...
focusNode: _titleFocus,
_descriptionFocus.requestFocus();
but it goes wrong and show the message ->
The following NoSuchMethodError was thrown while finalizing the widget tree:
The method 'dispose' was called on null.
Receiver: null
Tried calling: dispose()
Upvotes: 1
Views: 2854
Reputation: 14043
"When i want to create new one and passing focus one to another it's not working."
The FocusNode
doesn't get instantiated because of your condition in the initState
method. Hence the error (The method 'dispose' was called on null.
).
To fix, you can check for the condition before calling dispose()
on the FocusNode
s in the dispose
method.
@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();
}
UPDATE: Instead of the IF
checks, you could use the null aware operator
denoted by ?.
:
Added an example below:
@override
void dispose() {
// TODO: implement dispose
_titleFocus?.dispose();
_descriptionFocus?.dispose();
_todoFocus?.dispose();
}
super.dispose();
}
Upvotes: 5