Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why FocusNode needs to dispose in flutter?

Tags:

flutter

dart

I am kinda very confused when to use dispose in flutter. Are there any good tutorials about this?

In the cookbook https://flutter.io/docs/cookbook/forms/focus:

void dispose() {
  // Clean up the focus node when the Form is disposed
  myFocusNode.dispose();

  super.dispose();
}

Why do I have to call myFocusNode.dispose();? What happened if I don't call it?

Please explain a bit clear or give me some obvious bad code examples showing bad results when not to call dispose for FocusNode or other situations instead of simply telling me this will cause memory leak...

Thanks a lot.

like image 831
sgon00 Avatar asked Nov 14 '18 11:11

sgon00


1 Answers

As from the documentation:

Focus nodes are long-lived objects. For example, if a stateful widget has a focusable child widget, it should create a FocusNode in the State.initState method, and dispose it in the State.dispose method, providing the same FocusNode to the focusable child each time the State.build method is run. In particular, creating a FocusNode each time State.build is invoked will cause the focus to be lost each time the widget is built.

In other words, disposing them ensures that the node invokes focus correctly each time the widget is built, there are no issues with other Widgets which invoke focus and it also preserves performance.

like image 126
soupjake Avatar answered Oct 18 '22 02:10

soupjake