简体   繁体   English

如何检查 TextFormField 是否聚焦

[英]How to check whether TextFormField is focused or not

I have a TextFormField with focusNode:我有一个带有focusNode的TextFormField:

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).但是从文档中我看到TextFormField没有 'focusNode' 属性(如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. PS 我的意思是我们可以使用 FocusNode 侦听器,但我不想仅出于测试目的而这样做。 It should be really simply field.focusNode like for TextField.它应该真的很简单 field.focusNode 就像 TextField 一样。

You should add listener, where you can check state of your textFormField.您应该添加侦听器,您可以在其中检查 textFormField 的状态。 The method hasFocus return true or false.方法hasFocus返回 true 或 false。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM