How to debounce Textfield onChange in Dart?

This quick tutorial Contains How to debounce Textfield onChange in Dart. Which is super Simple

we use Debouncer while making a search text field where we need the letters typed in the fraction of mentioned time.

Users can add as many letters as they can in a Second depending upon the user’s typing Speed.

Here is our normal text Field

child: TextField(
        onChanged: (String value){

          },
        // ...
    )

in onChanged CallBack, we are getting data that is typed in the TextField but this onChanged Called every time when a user types any letter.

So we will make some changes inside this callBack Function but before that let’s create a Timer Variable.

Steps To create debounce Textfield onChange in Dart?

  • Create a Timer Variable
  • Inside The onChanged of TextField Create a Condition
  • if the timer variable is active then cancel the timer.cancel() fn
  • Next time = Timer() function which takes Duration and callBack function
  • That Call back function will call when the given Duration is over
  • Below is the Full Example Code for this

Import Statement

import 'dart:async';

Create the timer variable

Timer? _timer;

Now in onChanged function make a condition if the duration is active then cancel it and next create the delay effect.

child: TextField(
        onChanged: (String value){
                if (_timer?.isActive ?? false) _timer.cancel();
                _timer = Timer(const Duration(milliseconds: 500), () {
                 // add your Code here to get the data after every given Duration
           });
          },
        // ...
    )

Let’s say we need the data in the String variable after every second. Then Create the variable and inside the callback of the Timer function assign the value of the TextField to our variable.

String searchData;


TextField(
        onChanged: (String value){
                if (_timer?.isActive ?? false) _timer.cancel();
                _timer = Timer(const Duration(milliseconds: 500), () {

                searchData = value

           });
          },
        // ...
    )

Here is How Debouncer works. Copy the code and change the variables with yours and use it.

Thank you For Reading

Happy Fluttering


For more Flutter tutorials, Tips, Tricks, Free code, Questions, and Error Solving.

Remember FlutterDecode.com

Leave a Comment