Reputation: 1618
I am working on a slider in flutter which is focused on rating. I want to add a timer to manage a rating time (i.e if the user rated then he/she can't rate again for an hour. Which means once the function is triggered it won't trigger again for a specific time).
So how is it possible to do that. I have a little knowledge about the Timer
class and I don't how exactly it should be done. By doing this we are bounding the user not to rate as many times as user want
Upvotes: 1
Views: 440
Reputation: 6347
A simple implementation using a Timer
for the functionality you require is to store a bool
and start the timer and toggle the bool
value when the user performs the function and on timeout toggle the `bool to false and start the timer again.
Below is an example that uses setState
.
import 'dart:async';
import 'package:flutter/material.dart';
void main() {
runApp(MaterialApp(home:TimerExample()));
}
class TimerExample extends StatefulWidget{
@override
State<StatefulWidget> createState() {
return _TimerExampleState();
}
}
class _TimerExampleState extends State<TimerExample> {
// Using a short timer for testing, set a duration
// you can set a any duration you like, For Example:
// Duration(hours: 1) | Duration(minutes: 30)
final _timeoutDuration = Duration(seconds:3);
late Timer _timer;
bool _canVote = true;
@override
void dispose() {
super.dispose();
_timer.cancel();
}
void onTimeout() {
setState(() => _canVote = true);
}
void startTimer() {
setState(() {
_canVote = false;
_timer = Timer(_timeoutDuration, onTimeout);
});
}
@override
Widget build(BuildContext context) {
return TextButton(
onPressed: _canVote ? startTimer : null,
child: Text('Vote')
);
}
}
Upvotes: 2