mirkancal
mirkancal

Reputation: 5345

How to get which focusNode is currently focused in Flutter?

I need to know which focusNode is currently focused in Flutter.

Let me explain why I need that.

I'm using virtual_keyboard package because I have an issue with the numeric inputs.

            child: VirtualKeyboard(
          onKeyPress: (VirtualKeyboardKey key) {
            if (key.action == VirtualKeyboardKeyAction.Backspace) {
              _priceController.text = _priceController.text
                  .substring(0, _priceController.text.length - 1);
            }
            _priceController.text += key.text ?? "";
          },
          type: VirtualKeyboardType.Numeric,
        ),

I have two TextFormField's(price and amount) and when user changes the focus, onKeyPress: method needs to edit the text of another TextEditingController. If I know which focusNode is currently active, maybe I can do it.

Upvotes: 3

Views: 6033

Answers (3)

69 69
69 69

Reputation: 1

You can compare the FocusNode instance of a focusable widget (e.g. TextField) with FocusManager.instance.primaryFocus.

This was far more reliable, for me, than focusNode.hasFocus.

// initalize focusNode
FocusNode focusNode = FocusNode();

    
...
 
// add focusNode to TextField or any other fousable widget
child: TextField(
  focusNode: focusNode,
); 

... 

if(focusNode == FocusManager.instance.primaryFocus){
  // focusNode (TextField) is focused right now
}


     
                    

Upvotes: 0

alexkolykhalov
alexkolykhalov

Reputation: 121

Use FocusNode? _focusNode = FocusScope.of(context).focusedChild;

Upvotes: 3

Mangaldeep Pannu
Mangaldeep Pannu

Reputation: 3987

Refering to FocusNode

Use focusnode.hasFocus
It returns a true if node has input focus.

Upvotes: 1

Related Questions