Learn how to build a timer app using Getx. Create a controller and declare variables like below
class TimerController extends GetxController{
Timer? _timer;
int remainSeconds = 1;
final time = '00.00'.obs;
}
In the Controller we declared Timer object _timer, and remainSeconds for checking on the remaining seconds and then a time variable.
This time variable would be reactive. It means we Timer object’s return value would be saved time variable and our UI would be able to access and show it.
You see how tagged .obs with it.
_startTimer(int seconds){
const duration = Duration(seconds: 1);
remainSeconds = seconds;
timer_ = Timer.periodic(duration, (Timer timer) {
if(remainSeconds==0){
timer.cancel();
}else{
int minutes = remainSeconds~/60;
int seconds = remainSeconds%60;
time.value = minutes.toString().padLeft(2, "0")+":"+seconds.toString().padLeft(2, "0");
remainSeconds--;
}
});
}
In the _startTimer() we need to pass seconds as int type. That would be total time our UI should have.
Inside this Timer.periodic() is called. It takes to arguments, first one is how fast the timer should run, in this case we use 1 second as duration and second one a callback function.
That callback function should get call every other second.
From the UI call the time object and use like this
Text('${controller.time.value}')
The complete code
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
Get.put(TimerController());
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.indigo,
),
home: const HomePage());
}
}
// Home Page
class HomePage extends GetView<TimerController> {
const HomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
height: 100,
width: 200,
decoration: ShapeDecoration(
color: Theme.of(context).primaryColor,
shape: StadiumBorder(
side: BorderSide(
width: 2, color: Colors.red
)
)
),
child: Obx(
()=>Center(
child: Text('${controller.time.value}', style: TextStyle(
fontSize: 30, color: Colors.white,
),),
)
),
),
));
}
}
Complete code for the controller
class TimerController extends GetxController{
Timer? _timer;
int remainingSeconds =1;
final time = '00.00'.obs;
@override
void onReady(){
_startTimer(900);
super.onReady();
}
@override
void onClose(){
if(_timer!=null){
_timer!.cancel();
}
super.onClose();
}
_startTimer(int seconds){
const duration = Duration(seconds: 1);
remainingSeconds = seconds;
_timer = Timer.periodic(duration, (Timer timer) {
if(remainingSeconds==0){
timer.cancel();
}else{
int minutes = remainingSeconds~/60;
int seconds = (remainingSeconds%60);
time.value = minutes.toString().padLeft(2, "0")+
":"+seconds.toString().padLeft(2, "0");
remainingSeconds--;
}
});
}
}
Getx Firebase Chat App