I was wondering if it exists a way to continuously call a function on Flutter as long as a button (any kind of button is okay) is pressed.
For example:
GestureDetector(
child: Container(),
onLongPressStart: () {}, // Start of the function
onLongPressEnd: () {}, // End of the function
)
CodePudding user response:
Change your onLongPressEnd
to onLongPressUp
. So it should be like:
GestureDetector(
child: Container(),
onLongPressStart: () {},
onLongPressUp: () {}
);
CodePudding user response:
You could do something like
- on long tap, start the timer and call the function
- on long press end, stop the timer
Example:
Timer? timer;
GestureDetector(
onLongPressStart: (detail) {
setState(() {
timer = Timer.periodic(const Duration(milliseconds: 250), (t) {
print(Random().nextInt(1000) 9);
});
});
},
onLongPressEnd: (detail) {
if (timer != null) {
timer!.cancel();
}
},
child: Container(
child: const Text("press me"),
padding: const EdgeInsets.all(16),
color: kRedColor,
),
),
CodePudding user response:
You can use Timer
for this case.
//how often method will be called
Duration delay = const Duration(milliseconds: 100);
Timer? timer;
void continuousWork() {
debugPrint("I am working c ${timer!.tick}");
}
void onJobEnd() {
debugPrint("Job END");
timer?.cancel();
timer = null;
}
void onJobStart() {
if (timer != null) return;
debugPrint("Job started");
timer = Timer.periodic(delay, (timer) {
continuousWork();
});
}
And use case will be using GestureDetector
GestureDetector(
onTap: () {},
onTapDown: (details) {
onJobStart();
},
onTapUp: (v) {
onJobEnd();
},
child: Text("tap"),
),
More about dart-async
, and another way of doing this using CancelableOperation from async package