I am using a TextField
under which onChanged
function
I am calling my code but the issue right now is the code gets execute everytime a new word is either entered or deleted.
what I am looking for is how to recognize when a user has stopped typing.
means adding some delay or something like that.
I have tried adding delay
also using Future.delayed
function but that function also gets executed n number of times.
TextField(
controller: textController,
onChanged: (val) {
if (textController.text.length > 3) {
Future.delayed(Duration(milliseconds: 450), () {
//code here
});
}
setState(() {});
},
)
One possible way is to attach a keyup event to the input element and send an HTTP request for each character entered to the server to fetch search results: const input = document. querySelector('#input-text'); // Listen for `keyup` event input. addEventListener('keyup', (e) => { const text = e.
Executing a function after a certain amount of inactivity is known as debouncing. Debouncing can be helpful for many reasons. One of the most popular applications in web development is to execute a search or filter some results after a user has stopped typing text in a textbox.
Alternatively, use onblur event to see when the user clicks out of the textbox. yes, the delay should depend on how intensive the lookup is, how responsive you want it to be, and also: how fast your users normally type.
Thanks to @pskink
I was able to achieve the functionality I was looking for.
import stream_transform package in your pubspec.yaml
stream_transform: ^0.0.19
import 'package:stream_transform/stream_transform.dart';
StreamController<String> streamController = StreamController();
@override
void initState() {
streamController.stream
.transform(debounce(Duration(milliseconds: 400)))
.listen((s) => _validateValues());
super.initState();
}
//function I am using to perform some logic
_validateValues() {
if (textController.text.length > 3) {
// code here
}else{
// some other code here
}
}
TextField code
TextField(
controller: textController,
onChanged: (val) {
streamController.add(val);
},
)
In my case I also required flutter async.
//pubspec.yaml
stream_transform: ^2.0.0
import 'dart:async';
import 'package:stream_transform/stream_transform.dart';
StreamController<String> streamController = StreamController();
// In init function
streamController.stream
.debounce(Duration(seconds: 1))
.listen((s) => {
// your code
});
// In build function
TextField(
style: TextStyle(fontSize: 16),
controller: messageController,
onChanged: (val) {
myMetaRef.child("isTyping").set(true);
streamController.add(val);
},
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With