I wondering if there is any way to get a time interval for an item in Flutter?
Example:
I have an item where I set a date when this item was last calibrated, and then I want the application to remind me (with either a push message or an email) after a set period of time for the next calibration and so on.
I use Firestore for my database.
You may want to take a look to the Duration Dart's class.
Docs: https://api.dart.dev/stable/2.18.4/dart-core/Duration-class.html
To give you an idea, fast code example to initialize a span of time:
const fastestMarathon = Duration(hours: 2, minutes: 3, seconds: 2);
print(fastestMarathon.inDays); // 0
print(fastestMarathon.inHours); // 2
print(fastestMarathon.inMinutes); // 123
print(fastestMarathon.inSeconds); // 7382
print(fastestMarathon.inMilliseconds); // 7382000
You can look at the timeago package implementation to compare times.
dependencies:
timeago: ^3.3.0
You can use time ago for the exact purpose and it is quite beneficial. It has multiple formats and different language support as well.
import 'package:timeago/timeago.dart' as timeago;
main() {
final fifteenAgo = DateTime.now().subtract(Duration(minutes: 15));
print(timeago.format(fifteenAgo)); // 15 minutes ago
print(timeago.format(fifteenAgo, locale: 'en_short')); // 15m
print(timeago.format(fifteenAgo, locale: 'es')); // hace 15 minutos
}
Related
I am new to periodic background sync, What I want to achieve is that my website should ping to the server at 5 hours of interval by doing so It will receive data from server which will then be processed. I wanted to know if it's possible to set minInterval in periodic background sync to 5 hours or we can't. If their is another method to achieve this can you please give me some source or even an code example might be good.
In this following example of MDN they have set it to one day. Can I reduce it to 5 hours.?
async function registerPeriodicNewsCheck() {
const registration = await navigator.serviceWorker.ready;
try {
await registration.periodicSync.register('get-latest-news', {
minInterval: 24 * 60 * 60 * 1000,
});
} catch {
console.log('Periodic Sync could not be registered!');
}
}
Thanks for your help.
I am trying to get a switch widget to turn off at a specific time of the day.
I have read a lot of the documentations like these
https://stackoverflow.com/questions/15848214/does-dart-have-a-scheduler
https://pub.dev/packages/cron
https://pub.dev/packages/scheduled_timer
All of these which can only allow me to set duration instead of a specific time.
Thus, my only approach right now is by setting up the timer when the switch is turned on.
e.g. 8hrs then it turns off.
Problem: If the user turned on the switch late, the time that it turns off will also be delayed.
So is there an actual way to set an event at a specific time + works even after we onstop/terminate the application?
You can try to do something like this:
I'll simplify the specific time into :
...
var setTime = DateTime.utc(2022, 7, 11, 8, 48, 0).toLocal();
StreamSubscription? subscription;
...
Then you can assign a periodic stream listener:
...
// periodic to run every second (you can change to minutes/hours/others too)
var stream = Stream.periodic(const Duration(seconds: 1), (count) {
//return true if the time now is after set time
return DateTime.now().isAfter(setTime);
});
//stream subscription
subscription = stream.listen((result) {
// if true, insert function and cancel listen subscription
if(result){
print('turn off');
subscription!.cancel();
}
// else if not yet, run this function
else {
print(result);
}
});
...
However, running a Dart code in a background process is more difficult, here are some references you can try:
https://medium.com/flutter/executing-dart-in-the-background-with-flutter-plugins-and-geofencing-2b3e40a1a124
https://pub.dev/packages/flutter_background_service
I hope it helps, feel free to comment if it doesn't work, I'll try my best to help.
After some time I figured it out.
Format
cron.schedule(Schedule.parse('00 00 * * *'), () async {
print("This code runs at 12am everyday")
});
More Examples
cron.schedule(Schedule.parse('15 * * * *'), () async {
print("This code runs every 15 minutes")
});
To customize a scheduler for your project, read this
I'm developing a combobox using Flutter. combobox needs to be this month and next months. should write month name in combobox and return the number of the selected month. How can I do this in the shortest way?
I developed 12 months as DropdownMenuItem. I gave the current month as the default value. So far everything is fine. but how can I make the items of the past months invisible?
I used this code for a similar problem.
This solution includes intl package but you can change the code in list generation for your purpose.
import 'package:intl/intl.dart';
void main(){
var today = DateTime.now();
var length = 12 - today.month + 1; // I added +1 because I want to include current month too
List validMonths = List.generate(length,(index){
return DateFormat('MMMM').format(DateTime(0, (today.month + index)));
});
print(validMonths);
}
So, I have an app where users are reminded to take medicines every day at a particular time for a certain interval of dates. For example, the user can choose to get a notification from September 16,2020 to September 18,2020 at some time of the day
My approach : I schedule a notification using the flutter_local_notifications package with showDailyAtTime() function. However, the problem I face is that, suppose I don't open the app again, there is no way to cancel the scheduled notification and thus, the notification pops up even after the specified date range. I would like the notifications to be offline, so Firebase doesn't seem to be an option.
You can solve the problem with FlutterLocalNotificationsPlugin.
The approach would be to call the method rescheduleNotifications every time you start the app. In the method all notifications are removed and the next notifications are set. In calculateNotificationTimes for example you calculate all notifications for the next 30 days. For example, all notifications on September 16, 2020 to September 18, 2020 each day at a time of your choice.
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
Future<void> rescheduleNotifications() async {
final localNotificationsPlugin = FlutterLocalNotificationsPlugin();
const initializationSettings = InitializationSettings(AndroidInitializationSettings('app_icon'), IOSInitializationSettings());
const androidChannelSpecifics = AndroidNotificationDetails('your channel id', 'your channel name', 'your channel description');
const iOSNotificationDetails = IOSNotificationDetails();
const notificationsDetails = NotificationDetails(androidChannelSpecifics, iOSNotificationDetails);
await localNotificationsPlugin.initialize(initializationSettings);
await localNotificationsPlugin.cancelAll();
// Calculate the next notifications.
final notificationTimes = calculateNotificationTimes();
var _currentNotificationId = 0;
for (final time in notificationTimes) {
localNotificationsPlugin.schedule(
_currentNotificationId++,
"It's time to take your medicine.",
'Take the red pill',
time,
notificationsDetails,
androidAllowWhileIdle: true,
);
}
}
On iOS there is a limit that you can only have 64 notifications enabled. The disadvantage of this method on iOS is that if the user does not open the app after 64 notifications, no notification will be displayed. Which is fine, I think, because it seems that the user does not use the app anymore.
Did not test the code.
Is it possible if I have json with the timestamp like this
{
"modified": "2018-11-14T16:25:21",
}
and I want to make time ago in flutter. eg.5 minutes ago
import 'package:simple_moment/simple_moment.dart';
main() {
var datetoCompare = new Duration(seconds: 21,minute : 25, hour:16); //And so with month, year and Day.
var dateForComparison = new DateTime.now().add(datetoCompare);
var moment = new Moment.now();
print(moment.from(dateForComparison));
}
This Package helps in showing relative time in flutter.
Simple Moment package -
https://pub.dev/packages/simple_moment#-readme-tab-
For Seconds:
yourDate.difference(DateTime.now()).inSeconds;
For Minutes:
yourDate.difference(DateTime.now()).inMinutes;
For Hours:
yourDate.difference(DateTime.now()).inHours;