I have a flutter application with iterations,and in each iteration there is a countdown button.
When I click on the button the countdown of all the iterations work however my objective is to make only one countdown work.
Here is the countdown function:
int _countdownTime = 45;
late Timer _countdownTimer = Timer(Duration(seconds: 0), () {});
void startCountdownTimer() {
const oneSec = const Duration(seconds: 1);
_countdownTimer = new Timer.periodic(
oneSec,
(Timer timer) => setState(
() {
if (_countdownTime < 1) {
timer.cancel();
_countdownTime = 45; // Reset countdown timer to 45 seconds
} else {
_countdownTime = _countdownTime - 1;
}
},
),
);
}
void _handleCountdownTap() {
if (_countdownTimer == null || !_countdownTimer.isActive) {
startCountdownTimer();
}
}
here is the UI:
for (var breakdown in snapshot.data![index].breakdowns)
Card(
margin: EdgeInsets.zero,
child: Padding(
padding: EdgeInsets.only(bottom: 8.0, right: 8.0),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Expanded(
flex: 1,
child: Text(
'${breakdown.order}',
textAlign: TextAlign.center,
),
),
SizedBox(
height: 30,
child: GestureDetector(
onTap: _handleCountdownTap,
child: Container(
decoration: BoxDecoration(
color: Colors.blue,
borderRadius: BorderRadius.circular(8.0),
),
child: Center(
child: Text(
'$_countdownTime seconds',
style: TextStyle(
fontSize: 15,
color: Colors.white,
),
),
),
),
),
),
],
),
),
),
My question how to get only one countdown timer to work when clicked instead of all the iterations in the breakdown. Is there another solution or approach to fix this issue
2
Answers
You can create a widget which has timer logic on each item. Something like
Something like this?