【问题标题】:How to show alert dialog box only once in a day in Flutter?如何在 Flutter 中一天只显示一次警报对话框?
【发布时间】:2021-03-16 10:08:17
【问题描述】:
我正在开发一个应用程序,我想在其中添加一个功能,当用户打开该应用程序时,该功能每天只显示一次。我已经完成了我使用boolean variable 的对话框,如果此布尔值为true,则显示dialog,否则不显示dialog。一旦点击按钮打开对话框,我设置bool value to false。但我的问题是它将如何将true 再次设置为end of the day? 我应该怎么做才能在一天结束时再次将布尔值设置为true?
【问题讨论】:
标签:
java
android
ios
flutter
dart
【解决方案1】:
您需要上次显示对话框的日期/时间,而不是使用布尔值。
每次出现可能需要显示对话框的情况时,您会立即获取当前日期/时间,并将其与上次显示对话框的日期/时间进行比较。
因为您无法确定应用程序是否会被终止,所以您还需要存储该应用程序上次在磁盘上显示的日期/时间。
【解决方案2】:
您可以使用Shared Preferences 存储用户的上次访问时间,并检查用户今天是否在使用该应用。
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setInt('lastAccess', DateTime.now().millisecondsSinceEpoch)
// Get last access
final int lastAccess = prefs.getInt('lastAccess');
if(lastAccess!=null){
// Get last access as DateTime
final DateTime lastAccessTime = DateTime.fromMillisecondsSinceEpoch(lastAccess);
// Check if he opened the app
final opened = lastAccessTime.isAfter(DateTime.now());
if(!opened){
// Show Dialog
}
}
【解决方案3】:
我刚刚写了最简单的算法。
SharedPreferences prefs = await SharedPreferences.getInstance();
int? lastDay = prefs.getInt('lastDay');
int today = DateTime.now().day;
if (lastDay == null || lastDay != today) {
//Show the dialog
prefs.setInt('lastDay', today);
}
【解决方案4】:
timer = Timer.periodic(
Duration(days: 1,),
(Timer t) => {
//callback
});