Reputation: 21
Flutter how to run count down timer when the app is closed, I tried but timer each and every time starts from initial stage when I remove app from background
Upvotes: 0
Views: 1543
Reputation: 151
To run the countdown timer in the background, you can use the android_alarm_manager
package. This package allows you to schedule tasks that continue running even when the app is closed. By adding this package it with your countdown timer logic, you can ensure that the timer keeps running in the background.
please implement below code accordingly
import 'dart:async';
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Countdown Timer',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: CountdownScreen(),
);
}
}
class CountdownScreen extends StatefulWidget {
@override
_CountdownScreenState createState() => _CountdownScreenState();
}
class _CountdownScreenState extends State<CountdownScreen> {
int _duration = 60;
Timer _timer;
@override
void initState() {
super.initState();
startCountdown();
}
void startCountdown() {
_timer = Timer.periodic(Duration(seconds: 1), (timer) {
if (_duration <= 0) {
timer.cancel();
// Timer finished
print('Countdown complete!');
} else {
setState(() {
// Update timer display or perform other actions
print('Time remaining: $_duration seconds');
_duration--;
});
}
});
}
@override
void dispose() {
_timer?.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Countdown Timer'),
),
body: Center(
child: Text(
'Time remaining: $_duration seconds',
style: TextStyle(fontSize: 24),
),
),
);
}
}
I hope this is helpful for you.
Upvotes: 0