2

Right now I have a notification set up with local_notifications, problem is, it has the same body every single day.

How do I create daily notifications where the body is, for example, a random string from a list that is new each day?

This seems very common to have in apps, I have despite of that not found anything helpful so far.

Coder
  • 340
  • 1
  • 9

1 Answers1

0

Personally, I would save a variable with todays date using SharedPreferences and the DateTime package. Then, every time that you need to push a notification, I would compare today's date with the date that you've stored in Shared Preferences, and then return a random string from your list. Like so:

// call this when you want to send an notification
void pushDailyNotification(List<String> appStrings, SharedPreferences prefs) async {
   final random = Random();
   // random index from your list of strings
   int todayString = appStrings[random.nextInt(appStrings.length)]; 
   
   String savedDate = prefs.getString('date') ?? DateTime.now().toString();
   int today = DateTime.now().day;
   if(today != DateTime.tryParse(savedDate).day){ 
       // if the date that you've saved isn't the same as today's, its a new day, so return a new random string

       String newNotificationBody = appStrings[random.nextInt(appStrings.length)];

      await flutterLocalNotificationsPlugin.show(
    0, "It's a new day!", newNotificationBody, platformChannelSpecifics,
    payload: 'item x');
      prefs.setString('date', DateTime.now().toString());
      // save today's date for next time
   }
  else {
     // show a notification with the same body as last time
     await flutterLocalNotificationsPlugin.show(
    0, "It's a new day!", appStrings[todayString], platformChannelSpecifics,
    payload: 'item x');
  }

}

This may not fit with the exact setup of your project, but I hope this gives you an idea of what you could do. Use SharedPreferences and Random to help you.

Zachary Haslam
  • 103
  • 1
  • 12