Flutter:防止在键盘隐藏(后按)时调用 TextField 的 onChange

Pra*_*ani 6 flutter flutter-layout flutter-textinputfield

我正在研究 Flutter,基于搜索参数调用 API。

我所做的是:

  • 使用TextField创建的搜索框
  • onChange那个TextField 的,我已经调用了从服务器获取数据的方法。
  • 显示列表的 ListView

问题:当我使用 back press 完成搜索后隐藏键盘时,它再次请求获取数据。

你可以查看视频以获得更好的解释:

这是我的代码:

getTextInputField() {
    return Flexible(
      fit: FlexFit.tight,
      flex: 1,
      child: TextFormField(
        controller: _text,
        decoration: new InputDecoration(
          labelText: "Enter Area for Pincode",
          fillColor: Colors.white,
          errorText: _validateAgain ? 'This should not be empty!' : null,
          border: new OutlineInputBorder(
            borderRadius: new BorderRadius.circular(15.0),
            borderSide: new BorderSide(),
          ),
          //fillColor: Colors.green
        ),
        validator: (val) {
          if (val.length == 0) {
            return "This shouldn't be empty!";
          } else {
            return null;
          }
        },
        onChanged: (value) {
          getData();
        },
        keyboardType: TextInputType.streetAddress,
      ),
    );
  }

getData() {
    setState(() {
      if (_text.text.isNotEmpty) {
        if (_text.text.length > 2) {
          _validateAgain = false;
          textValue = _text.text;
          _apiCall = true;
          _callAPIForPinCode();
        }
      } else
        _validateAgain = true;
    });
  }
Run Code Online (Sandbox Code Playgroud)

当我使用后按隐藏键盘时如何防止再次调用 API

注意:如果我使用键盘上的完成键隐藏键盘,则不会调用 API 并顺利隐藏。

编辑:

由于我现在已经离线测试,它也在离线调用。它在关闭键盘时调用onChange事件。

Ami*_*aei 5

跟踪上次搜索的文本并比较从 onChange 回调到达的 newText,如果它们不同,则可以执行 searchApi 函数

例如 :

class _PageAState extends State<PageA> {
  String lastInputValue;

  @override
  Widget build(BuildContext context) {
    return Center(
      child: TextField(
        onChanged: (inputValue) {
          if (lastInputValue != inputValue) {
            lastInputValue = inputValue;
            print("New value inserted in textField $inputValue");
          }
        },
      ),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

此代码仅在文本字段的值实际更改时才打印,并且不会对键盘更改或其他可以调用 onChange 方法的事情做出反应

为什么会这样?

发生这种情况是因为您正在撰写的文本范围发生了更改 当您在用空格分隔的两个单词之间更改光标时将发生此事件 当您单击第一个时 onChange 将被调用,当您单击换句话说 onChange 回调将被调用

您可以在第 2242 行看到 EditableTextState 和 _formatAndSetValue 函数的 SDK 源代码,该函数负责调用 onChange 回调,为此它接收一个 TextEditingValue 对象,该对象包含有关在 TextField 中发生的更改的信息,例如它包含文本属性它指的是更改或选择属性后的 TextFild 文本,该属性指的是用户选择了哪些字符,以及指的是仍在编写的文本范围的 TextRange 属性,并且在 _formatAndSetValue 中,它正在检查要调用的条件onChangeMethod 第一个是查看文本是否与之前的 TextFiled 文本不同,第二个是检查 Composing 范围是否与之前的 Composing 范围不同

因此,当您单击文本字段或事件空文本字段中的单词并打开键盘时,组合范围更改为您单击的单词或部分,当您关闭键盘时,组合范围更改为 -1,-1,这意味着它是空的