Flutter Button It should be pressed once in a day

Issue

Is there any where I can make a button to be pressed only once in a day.
You cannot press that button again in that day.
you need to wait till next day inorder to press it again

                  ElevatedButton(
                      onPressed: () {
                        print("Once in a day");
                        title = "Change Date";
                      },
                      child: Text(title),
                    ),

Solution

Add below code in your onPress function,

ElevatedButton(
  onPressed: () {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    final currentTime = DateTime.now();
    DateTime resetTime = DateTime.parse(prefs.getString("time"));
    
    if(resetTime != null && !compareDate(currentTime, resetTime))
                                    prefs.setBool("one_tap", true);
                                  
      if(prefs.getBool("one_tap") == null || prefs.getBool("one_tap")){
          print("Once in a day");
          title = "Change Date";
          prefs.setBool("one_tap", false);
          prefs.setString("time", currentTime.toString());
         }
},
child: Text(title),),

compareDate(DateTime current, DateTime reset) {
    if (reset != null) {
      return current.year == reset.year &&
          current.month == reset.month &&
          current.day == reset.day;
    } else {
      return true;
    }
  }

Answered By – Bhoomika Chauhan

Answer Checked By – Dawn Plyler (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.