Search code examples
androidflutterdatetimesharedpreferences

How to convert String to Time in Hour, Minute, Second as integer in flutter?


I am making an app in that I want to send a notification to the user with the help of the flutter_local_notification package. I want to send a notification to the user at a certain time every day, for that, I am using the following function:

Future<void> showDailyAtTime() async {
////////// <<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>
var time = Time(16, 02, 00); ////// line 1 <---------- (Hour, Minute, Second)
////////// <<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>
var androidChannelSpecifics = AndroidNotificationDetails(
  'CHANNEL_ID 2',
  'CHANNEL_NAME 2',
  "CHANNEL_DESCRIPTION 2",
  importance: Importance.max,
  priority: Priority.high,
);
var iosChannelSpecifics = IOSNotificationDetails();
var platformChannelSpecifics =
NotificationDetails(android: androidChannelSpecifics, iOS: iosChannelSpecifics);
await flutterLocalNotificationsPlugin.showDailyAtTime(
  0,
  'Test Title at ${time.hour}:${time.minute}.${time.second}',
  'Test Body', //null
  time,
  platformChannelSpecifics,
  payload: 'Test Payload',
 );
}

I am storing the time using shared preferences like this:

ttime = '${time.hour} : ${time.minute} : ${time.second}';

And then I am setting it like this:

Future<void> _setNotifyTime() async{
final prefs = await SharedPreferences.getInstance();
final savedNotifyTime = await _getStringFromSharedPrefs();
await prefs.setString('notificationTime', ttime);
//print("this $savedNotifyTime");
return savedNotifyTime;
}

Then I am getting from shared preferences with the help of following code:

Future<String> _getStringFromSharedPrefs() async{
final prefs = await SharedPreferences.getInstance();
notifyTime = prefs.getString('notificationTime');
return notifyTime;
}

How can I convert this saved time to the required format (as shown in line 1), the values are in int? How can I do it? Please help me.

Thanks for your replies in advance


Solution

  • var splited = notifyTime.split(':');
    int hour = int.parse(splited[0]);
    int minute = int.parse(splited[1]);
    int second = int.parse(splited[2]);