How to check whether TextFormField is focused or not

Viewed 2256

I have a TextFormField with focusNode:

TextFormField(
   key: Key('login-username-field-key'),
   controller: loginTextController,
   textInputAction: TextInputAction.next,
   keyboardType: TextInputType.text,
   onFieldSubmitted: (term){
      _changeFocusField(context, _loginFocus, _passwordFocus);
   },
   focusNode: _loginFocus,
   decoration: InputDecoration(
   labelText: AppLocalizations.of(context).loginFieldUsername
   ),
),

And then:

// Check that text field initially is not focused
final TextFormField textField = tester.widget(find.byKey(Key('login-username-field-key')));
expect(textField.focusNode.hasFocus, isFalse);

But from the docs I saw that TextFormField doesn't have 'focusNode' property (like TextField.focusNode.hasFocus).

So how to check that behavior?

PS I mean we can use FocusNode listeners, but I don't want to do that just for testing purposes. It should be really simply field.focusNode like for TextField.

1 Answers

You should add listener, where you can check state of your textFormField. The method hasFocus return true or false.

@override
  void initState() {
    super.initState();
    _loginFocus.addListener(_onFocusChange);
  }

  void _onFocusChange(){
    debugPrint("Focus: "+_focus.hasFocus.toString());
  }
Related