When Flutter clicks outside the input box, the input box loses focus

1. Description of requirements

When the input box is clicked, the input box can get the focus, and when a place outside the input box is clicked, the input box loses focus.

Two, the solution

1. Initialize focusNode, FocusNode focusNode = FocusNode()

2. Set focusNode for the input box TextField

3. Call focusNode.unfocus() in the onTapOutside event

4. Release the focusNode before the component is destroyed, focusNode.dispose()

Note: If the version of the Flutter SDK is too low, there will be no onTapOutside event, just update the Flutter SDK.

3. Code sharing

class _SearchInput extends State<SearchInput> {
  ///编辑控制器
  late TextEditingController _controller;

  /// 是否显示删除按钮
  bool _hasDeleteIcon = false;

  /// 输入框焦点
  FocusNode focusNode = FocusNode();

  @override
  void initState() {
    super.initState();
    _controller = TextEditingController();
  }

  @override
  Widget build(BuildContext context) {
    return TextField(
      controller: _controller,
      textInputAction: TextInputAction.search,
      textAlignVertical: TextAlignVertical.center,
      keyboardType: TextInputType.text,
      focusNode: focusNode,
      onTapOutside: (e) => {
        focusNode.unfocus()
      },
      onEditingComplete: () {
        FocusScope.of(context).requestFocus(focusNode);
      },
    );
  }

  @override
  void dispose() {
    super.dispose();
    _controller.dispose();
    focusNode.dispose();
  }
}

4. Reference:

The use of focus FocusNode in Flutter to analyze the capture and monitoring of the focus event of the Flutter input box Develop Paper

Guess you like

Origin blog.csdn.net/m0_68349563/article/details/129498002