For example, I want to execute some function after 2 hours from the current time on the device (I did this using Timer()). But I want if I change the time on the device faster than 2 hours, those functions will execute immediately instead of waiting 2 hours. Please tell me the solution. Thank you !
CodePudding user response:
Use shared preferences package
https://pub.dev/packages/shared_preferences
When you wish to start the timer get the datetime and save it in shared preferences
SharedPreferences _prefs = await SharedPreferences.getInstance();
_prefs.setString('startTime', DateTime.now().toString());
Now to check the difference
DateTime startTime = DateTime.parse(_prefs.getString('startTime'));
if(startTime.add(Duration(hours:2)).isBefore(DateTime.now())
{
print("2 hours are over");
}
If you wish to check it every second add the checker in a periodic timer of duration 1 second