Question

How to decrease specific time from DateTime.now() in flutter?

I want a timer to decreasing become time from current time. i.e. this is my beginning time '05:23:23' and if the the current time or DateTime.now() is going up my time should goes to come down, and if I am going to close the app for 05min and 13sec, and opening the app' timer should not start from the beginning '05:23:23' the up should start from the passed times '05:18:10'.

 2  70  2
1 Jan 1970

Solution

 1
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'),
    );
  }
}
2024-07-23
Shlomo Cardoso