final startTime = DateTime.now();
final duration = // amount of time for the timer
final endTime = startTime.add(duration);
final timer = Timer.periodic(const Duration(seconds: 1), (timer) {
print(endTime.difference(startTime));
});
you need to save endTime in shared preferences to save the timer when the app is closed
Edit: complete example
late final prefs;
main () async {
// initialize shared preferences (you need to add the package to pubspec.yaml and import it)
prefs = await SharedPreferences.getInstance();
runApp(MyApp());
}
class MyStatefulWidget extends StatefulWidget {
const MyStatefulWidget({super.key});
@override
State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
Timer? timer;
Duration? timerDuration;
@override
void initState() {
// get current timer from shared preferences if exists
final endTime = prefs.getInt('end_time');
if (endTime != null) {
activateTimer(DateTime.fromMillisecondsSinceEpoch(endTime));
}
super.initState();
}
@override
void dispose() {
timer?.cancel();
super.dispose();
}
activateTimer(DateTime endTime) {
callback(timer) {
setState(() {
timerDuration = endTime.difference(DateTime.now());
});
}
callback(timer);
timer = Timer.periodic(const Duration(seconds: 1), callback);
}
startNewTimer() {
final endTime = DateTime.now().add(duration);//todo: set the duration
// save in shared preferences
prefs.setInt('end_time', endTime.millisecondsSinceEpoch);
activateTimer(endTime);
}
@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: startNewTimer,
child: Text('$timerDuration'),
);
}
}