timeAgoNotifier property
ValueNotifier<String>
get
timeAgoNotifier
Returns a ValueNotifier that updates the relative time string periodically.
Example:
final date = DateTime.now();
final notifier = date.timeAgoNotifier;
// returns: ValueNotifier('just now')
Implementation
ValueNotifier<String> get timeAgoNotifier {
final key = millisecondsSinceEpoch.toString();
// get cached notifier if available
final cachedNotifier = _timeAgoNotifiers[key];
if (cachedNotifier != null) return cachedNotifier;
// compute ago time
String _compute() {
final d = DateTime.now().difference(this);
if (d.inSeconds <= 0) return 'just now';
final weeks = d.inDays ~/ 7;
final days = d.inDays;
final hours = d.inHours;
final minutes = d.inMinutes;
final seconds = d.inSeconds;
if (weeks > 0) return '${weeks}w ago';
if (days > 0) return '${days}d ago';
if (hours > 0) return '${hours}h ago';
if (minutes > 0) return '${minutes}m ago';
return '${seconds}s ago';
}
// create notifier
final notifier = ValueNotifier(_compute());
final isRecent = DateTime.now().difference(this).inSeconds < 3600;
// cache notifier and run timer if this date is less than 1 hour old
if (kIsWeb && isRecent) {
_timeAgoNotifiers[key] = notifier;
Timer.periodic(const Duration(seconds: 1), (timer) {
// if this date is now more than 1 hour old, cancel timer
// and remove notifier from memory cache
if (DateTime.now().difference(this).inHours >= 1) {
timer.cancel();
_timeAgoNotifiers.remove(key);
return;
}
// update notifier value
notifier.value = _compute();
});
}
return notifier;
}