简体   繁体   English

如何在 Flutter 中一天只显示一次警告对话框?

[英]How to show alert dialog box only once in a day in Flutter?

I'm working on an app in which I want to add a functionality that shows an alert dialog box only once a day when the user opens the app.我正在开发一个应用程序,我想在其中添加一个功能,该功能每天仅在用户打开应用程序时显示一次警报对话框。 I'm done with the dialog box I used the boolean variable if this bool value is true then show dialog else don't show the dialog .我完成了我使用boolean variable的对话框,如果此布尔值为true ,则显示对话框,否则不显示对话框 Once the dialog opens on tap of the button I set the bool value to false .一旦点击按钮打开对话框,我将bool value to false But my question is how it will set true again at the end of the day?但我的问题是它如何在一天结束时再次变为true end of the day? What should I need to do so the bool value again set to true at the end of the day?我应该怎么做才能在一天结束时再次将布尔值设置为 true?

Instead of using a boolean, you need the last date/time the dialog was shown.您需要上次显示对话框的日期/时间,而不是使用 boolean。

Every time a situation occurs in which you may need to show the dialog, you get the current date/time now and compare that with date/time of the last dialog showing.每次出现您可能需要显示对话框的情况时,您都会立即获取当前日期/时间,并将其与上次显示对话框的日期/时间进行比较。

Because you can't be sure if the app will be killed or now, you also need to store the last date/time the app was shown on disk.因为您无法确定应用程序是否会被终止,所以您还需要存储应用程序在磁盘上显示的最后日期/时间。

You could store the last access time of the user with Shared Preferences and check if the user was using the app today.您可以使用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
      }
    }

I just wrote the easiest algorithm.我只是写了最简单的算法。


 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);
    }
timer = Timer.periodic(
 Duration(days: 1,), 
 (Timer t) => {
  //callback
 });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM