10

I am a new to flutter and there was nothing in which explained what
FocusScope.of(context).requestFocus(FocusNode());

actually does. I looked through the Flutter documentation but could not figure out exactly what this means.

Can anyone explain this to me?

Every single detail will help. Thank You.

Suraj M
  • 171
  • 2
  • 9

1 Answers1

10

What you have found is an outdated way to hide the keyboard on older versions of Flutter. If you want to hide the keyboard using modern version, see this answer: https://stackoverflow.com/a/56946311/11382675

Back to this code.

FocusScope is a widget that is automatically created for you somewhere up the tree. It keeps focus traversal to only widgets underneath it in the tree. Without this widget, in a modal dialog you could have moved the focus to a screen behind it.

FocusScope.of(context) takes the current widget position in the tree (this is what context is) and walks up the tree to find the nearest FocusScope widget.

Then the requestFocus method on the found FocusScope widget causes the focus to move to an object that you pass.

Since you want to focus on nothing (to make the keyboard go away), you pass a newly created FocusNode object that is not associated to any widget. It is disposable and is destroyed afterwards.

FocusNode objects are used to set focus on input controls. If you create one and keep a reference to it in your State, you can pass it to TextFormField widget as focusNode: _myFocusNode and then use it as a handle to set focus on that input.

Alexey Inkin
  • 1,853
  • 1
  • 12
  • 32