I want to display a message to a user once a day on login. I'm aware that we can use .difference().inDays >= 1 to compare 2 DateTimes show the message if true. Where I am confused is which 2 DateTimes we should be comparing. I currently use DateTime.now() and a function that returns the last login time. The issue with this is that the last login time will get updated every time the user logs in. Here is what my function looks like:
Future<void> showDialog() async {
if (Client.loginResponse.loginMessage[0].message != '') {
if (DateTime.now()
.difference(await MobileLoginCache.getLastLogin(
Client.loginResponse.dataSource, Client.loginResponse.user.name, localStorage))
.inDays >=
1) {
await LoginMessageDialog(content: Client.loginResponse.loginMessage[0].message, context: context).show();
}
}
}
What should I use instead of the last login time?
You could probably just keep the DateTime when you showed your dialog in SharedPreferences?
Future<void> showDialog() async {
if (Client.loginResponse.loginMessage[0].message != '') {
SharedPreferences prefs = await SharedPreferences.getInstance();
DateTime now = DateTime.now();
DateTime lastMessageTime = new DateTime(prefs.getLong("lastMessageTime", 0));
if (now.difference(lastMessageTime).inDays >= 1) {
await prefs.setLong("lastMessageTime", now.getTime());
await LoginMessageDialog(content: Client.loginResponse.loginMessage[0].message, context: context).show();
}
}
}