Home > Software design >  How can I limit the number of actions performed by a user every 24 hours?
How can I limit the number of actions performed by a user every 24 hours?

Time:12-30

I have a button that provides a reward to users. I want users to have the option to press the button up to 2 times every 24 hours. Is it possible to implement this without making users sign in?

One possible way to achieve this is by using Firebase and keeping track of the number of times a user has pressed the button and reset it every 24 hours. I believe this does require users to sign in, though, which is not ideal. Also, I don't think this is a very good way to solve my problem.

EDIT: local storage like shared preference may work out, but if the user clears the app cache, the data stored in shared preferences will be deleted as well. This means that the button press counter and time will be reset, and the user will be able to press the button up to 2 times again.

Is there any other way to achieve this?

CodePudding user response:

You can use the shared_preferences plugin to keep track of different things.

This plugin will persist the data even if the app is closed.

Code example

create a method to save the last time:

Future<void> _saveLastActionTime() async{
  SharedPreferences prefs = await SharedPreferences.getInstance();
  await prefs.setInt('lastActionTime', DateTime.now().millisecondsSinceEpoch);

}

And now to retrieve it:

Future<int?> _getLastActionTime() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  return prefs.getInt('lastActionTime');
}

To get check whether the last action was more then 24hours ago:

Future<bool> _isLastActionMoreThan24HoursAgo() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  int? lastActionTime = prefs.getInt('lastActionTime');
  if (lastActionTime == null) {
    return true;
  }
  DateTime lastActionDateTime = DateTime.fromMillisecondsSinceEpoch(lastActionTime);
  return DateTime.now().difference(lastActionDateTime).inHours > 24;
}
  • Related