Skip to content

Instantly share code, notes, and snippets.

@GAM3RG33K
Last active May 7, 2021 06:39
Show Gist options
  • Save GAM3RG33K/ba8eafadb83c3d6f3b9808971d618e44 to your computer and use it in GitHub Desktop.
Save GAM3RG33K/ba8eafadb83c3d6f3b9808971d618e44 to your computer and use it in GitHub Desktop.
[Flutter] A countdown timer widget using overlay [With color animation]
import 'package:flutter/material.dart';
import 'package:timer_count_down/timer_count_down.dart';
class CountdownTimer extends StatefulWidget {
final Duration timerDuration;
final VoidCallback onComplete;
final String Function(double seconds) formatTimerString;
final Color startColor;
final Color endColor;
CountdownTimer({
Key key,
@required this.timerDuration,
this.onComplete,
this.formatTimerString,
this.startColor = Colors.green,
this.endColor = Colors.red,
}) : super(key: key);
@override
_CountdownTimerState createState() => _CountdownTimerState();
}
class _CountdownTimerState extends State<CountdownTimer> {
ColorTween _colorTween;
@override
void initState() {
// tween values will be shown in reverse as the timer is going backwards
_colorTween = ColorTween(
begin: widget.endColor,
end: widget.startColor,
);
super.initState();
}
@override
void dispose() {
super.dispose();
}
int get totalDurationInSeconds => widget.timerDuration.inSeconds;
@override
Widget build(BuildContext context) {
return Countdown(
seconds: totalDurationInSeconds,
build: (context, countDownSeconds) {
final currentProgress = _calculateProgress(
totalDurationInSeconds,
countDownSeconds,
);
final timerString = buildTimerString(countDownSeconds);
return SafeArea(
child: SizedBox(
height: 8,
child: Stack(
alignment: Alignment.topCenter,
children: [
Container(
color: _colorTween.lerp(currentProgress),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Padding(
padding: EdgeInsets.symmetric(vertical: 2),
child: Text(
timerString,
style: TextStyle(
fontSize: 14,
color: Colors.white,
fontWeight: FontWeight.w700,
),
),
),
],
),
),
],
),
),
);
},
onFinished: () {
widget.onComplete?.call();
},
);
}
buildTimerString(double seconds) {
if (widget.formatTimerString != null) {
return widget.formatTimerString(seconds);
}
// format the string manually
final rawMinutes = seconds / 60;
final remainingMinutes = rawMinutes.toInt();
final remainingSeconds = (seconds % 60).toInt();
return '${remainingMinutes == 0 ? '' : '$remainingMinutes m '}$remainingSeconds s';
}
double _calculateProgress(
int totalDurationInSeconds, double countDownSeconds) {
var progress = (countDownSeconds / totalDurationInSeconds);
if (progress >= 1) progress = 1;
return progress;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment