首页 > 解决方案 > Flutter 中的 FocusNode 'node.ancestors.contains(this)' 错误

问题描述

        TextEditingController _currentPasswordController = TextEditingController();
        TextEditingController _newPasswordController = TextEditingController();
        FocusNode _currentPasswordFocus = FocusNode();
        FocusNode _newPasswordFocus = FocusNode();   
    //---------------------------------------------------

    PasswordField(
            controller: _currentPasswordController,
            autoFocus: true,
            focusNode: _currentPasswordFocus,
            maxLength: 20,
            ),

        PasswordField(
            autoFocus: false,
            focusNode: _newPasswordFocus,
            maxLength: 20,
            onSaved: (newValue) {
               setState(() {
                    newPassword = newValue;
                        });
                       },
            controller: _newPasswordController,
            )     


  //Save Button-->      
        onPressed: () {
               if (formKey.currentState.validate()) {
                 formKey.currentState.save();
                   if (_currentPasswordController.text != _newPasswordController.text) {
                     FocusScope.of(context).autofocus(_currentPasswordFocus);
                      ..................
                       ...................... 
                  }
             }

如果在上面的代码示例中按下按钮时文本表单字段值不相等,我希望光标聚焦在 _currentPasswordController 字段上。

它在发布模式下的真实设备上运行良好。但是我在调​​试模式下在模拟器上收到此错误消息。

Autofocus was requested for a node that is not a descendant of the scope from which it was requested.
'Package: flutter / src / widgets / focus_manager.dart':
Failed assertion: line 1024 pos 14: 'node.ancestors.contains (this)'

标签: flutterdartautofocus

解决方案


推荐阅读