Home > Mobile >  How to store TimeofDay in shared preferences
How to store TimeofDay in shared preferences

Time:03-21

I'm trying to store time picked from showTimePicker in shared preferences permanently, but am unable to do it

here is my code


 void saveData(String key, String value) async {
   final prefs = await SharedPreferences.getInstance();
   await prefs.setString(key, value);
 }


 Future tweetTimePicker(BuildContext context) async {
   TimeOfDay initialTime = const TimeOfDay(hour: 9, minute: 0);
   final showDate = await showTimePicker(context: context, initialTime: initialTime);

   if(showDate != null){
     setState(() {
       saveData('primaryTweetTime', showDate.toString());
       tweet_time = showDate;
     });
   }
 }

 void getTime() async {
   final prefs = await SharedPreferences.getInstance();
   final value = prefs.getString('primaryTweetTime');
   DateTime tweetTiming = DateTime.parse(value!);
   TimeOfDay tweetTime = TimeOfDay(hour: tweetTiming.hour, minute: tweetTiming.minute);

   TimeOfDay tweetTime = TimeOfDay.fromDateTime(tweetTiming); // tried this too but didn't worked
   setState(() {
     tweet_time = tweetTime; // still shows initial time
   });
 }

CodePudding user response:

You can do it as folllows: when saving -> saveData("primaryTweetTime", showDate.hour.toString() ":" showDate.minute.toString()); when retrieving -> TimeOfDay tweetTime = TimeOfDay(hour: value.split(":")[0], minute: value.split(":")[1]);

CodePudding user response:

The best option is just to store it as a String:

final now = DateTime.now();
final prefs = await SharedPreferences.getInstance();
await prefs.setString('primaryTweetTime', now.toString());

To get it back:

final prefs = await SharedPreferences.getInstance();
final value = prefs.getString('primaryTweetTime');
final dateTime = DateTime.parse(value!);

CodePudding user response:

You need to convert it to String before store it to Shared Preferences.

Step 1, declare and initialize date time variables

DateTime now = DateTime.now();

Step 2, initialize shared pref instance

final sharedPrefs = await SharedPreferences.getInstance();

Step 3, store it to sharedPref

await sharedPrefs.setString('currentTime', now.toString());

Step 4, you can retrieve it like this

String currentTimeData = await sharedPrefs.getString('currentTime');

And dont forget, it's still a String. To use it as a DateTime, you should convert it back to DateTime like this

DateTime data = DateTime.parse(currentTimeData);

Thats all, hope this helps

  • Related