Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter: Prevent to call onChange of TextField when Keyboard hide (Back Press)

I am working on Flutter, Calling API based on Search Parameters.

What I have done is:

  • Search Box created using TextField
  • onChange of that TextField, I have called method to get data from server.
  • ListView displaying a list

Problem: When I hide the keyboard after my searching is done using back press, It's requesting again to get data.

You can check video for better explanation:

Here is my code:

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;
    });
  }

How I prevent calling API again when I hide the keyboard using back press.

Note: If I hide the keyboard using the done key from the keyboard, it's not calling API and hiding smoothly.

Edited:

As I have tested offline right now, It's calling offline too. It's calling the event of onChange on dismissing the keyboard.

like image 953
Pratik Butani Avatar asked Apr 03 '21 09:04

Pratik Butani


People also ask

How do I hide the keyboard in TextField Flutter?

TextField is a very common widget in Flutter. When you click on the TextField it opens up the on-screen keyboard. To hide/dismiss the keyboard you have to press the back button in Android and the done button (inside the onscreen keyboard) in iOS.

How do I hide the Underfield of a TextField in Flutter?

To remove TextField underline/border in Flutter, you can simply set the border property to InputBorder. none. This will remove the underline for all states such as Focused, Enabled, Error, Disabled.

Does tapping outside a text field hide the keyboard in flutter?

However, tapping outside a text field doesn't hide the keyboard by default. If you want to make the keyboard disappear by tapping outside, it can be done with ease. Below you can read the explanation and examples. When a user taps on a text field, Flutter automatically changes the current focus to the tapped text field.

How to prevent soft keyboard from covering textfield while typing?

To prevent the soft keyboard from covering your TextField while the user is typing, you can wrap your main widget with SingleChildScrollView. In case you place some text fields inside a bottom sheet and want to avoid the soft keyboard overlapping the text fields, see this example: Modal Bottom Sheet with TextFields inside.

How to make flutter textfield lose focus on listview scroll?

Suppose you have a Listview with lists of widget (Text Input Field) in it, then user fill the textfield and scroll down, than the keyboard should get dismissed and flutter textfield lose focus on listview scroll. In that case you can make user of Listview keyboardDismissBehaviour with ScrollViewKeyboardDismissBehavior.onDrag

How to hide on-screen keyboard when the user taps outside text field?

That's how to hide the on-screen keyboard when the user taps outside a text field. You need to remove the focus from the text field when the user taps outside a text field which can be done with the help of GestureDetector or Listener.


Video Answer


1 Answers

keep track of the last searched text and compare newText that arrives from the onChange callback and if they are different then you can execute searchApi function

for example :

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");
          }
        },
      ),
    );
  }
}

this code only prints if the value of the text field is actually changed and it's not reacting to the keyboard changes or other things that can invoke the onChange method

Why This is happening?

it is happening because the range of the text that you were composing is changed this event will happen when you change the cursor between two words that are separated with space when you click on the first one onChange will be invoked and again when you click on the other word onChange callback going to be invoked

you could see SDK source code for EditableTextState and the _formatAndSetValue function at line 2242 this function is responsible for invoking the onChange callback and for this it is receiving a TextEditingValue object which contains information about the changes that are happened in TextField for example it contains text property which refers to the TextFild text after a change or selection property that refers to the which chars are selected by the user and also a TextRange property that refers to the range of text that is still being composed and in the _formatAndSetValue it is checking conditions to invoke the onChangeMethod The first one is to see if the text differs from the previous TextFiled text and the second one is to check to see if the Composing range differs from the previous Composing range

so when you click on a word in the text field or event empty text field and keyboard opens up the composing range is changed to that word or section which you click and when you close the keyboard composing range is changed -1,-1 which means it is empty

like image 125
Amir Hossein Mirzaei Avatar answered Oct 03 '22 17:10

Amir Hossein Mirzaei