简体   繁体   中英

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

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

You can do pattern splitting like in the answer by Jorge Vieira or you save yourself the parsing logic and just store it as ints.


For setting you can use setInt()

prefs.setInt("H",time.hours);
prefs.setInt("m",time.minutes);
prefs.setInt("s",time.seconds);

For getting it you can use getInt()

int hours = prefs.getInt("H");
int mins = prefs.getInt("m");
int secs = prefs.getInt("s");

Then from your methods just return the Time object

return Time(hours,mins,secs);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM