首页 > 解决方案 > 无法检测到 Textfield unfocus lister

问题描述

如何检测 textField 何时失去焦点?我尝试用谷歌搜索它,但只找到了检测文本字段何时聚焦的方法。

TextField(
      keyboardType: TextInputType.text,
      minLines: 2,
      maxLines: null,
      controller: fieldController,
    ),

标签: flutter

解决方案


只需使用FocusNodeaddListener方法,如下所示:

//define _node and _focused virables in header class
FocusNode _node = FocusNode(); 
bool _focused = false;

//handleFocusChange in initState method
  @override
  void initState() {
    super.initState();
    _node.addListener(_handleFocusChange);
  }

 void _handleFocusChange() {
    if (_node.hasFocus != _focused) {
      setState(() {
        _focused = _node.hasFocus;
      });
    }
  }

//use _node in TextField
TextField(
      keyboardType: TextInputType.text,
      minLines: 2,
      maxLines: null,
      focusNode:_node,
      controller: fieldController,
    ),

推荐阅读