import 'dart:async'; import 'package:flutter/widgets.dart'; import 'relative_time.dart'; /// A relative-time label that rebuilds only itself when its formatter can /// change. It stops its timer while the app is backgrounded. class RelativeTimeLabel extends StatefulWidget { const RelativeTimeLabel({super.key, required this.instant, this.now}); final DateTime? instant; final DateTime? now; @override State createState() => _RelativeTimeLabelState(); } class _RelativeTimeLabelState extends State with WidgetsBindingObserver { Timer? _timer; DateTime _now = DateTime.now(); @override void initState() { super.initState(); WidgetsBinding.instance.addObserver(this); _schedule(); } @override void didUpdateWidget(RelativeTimeLabel oldWidget) { super.didUpdateWidget(oldWidget); if (oldWidget.instant != widget.instant) _schedule(); } @override void didChangeAppLifecycleState(AppLifecycleState state) { if (state == AppLifecycleState.resumed) { _now = DateTime.now(); if (mounted) setState(() {}); _schedule(current: _now); } else if (state == AppLifecycleState.hidden || // Not inactive: a desktop window that lost focus is still visible. state == AppLifecycleState.paused || state == AppLifecycleState.detached) { _timer?.cancel(); _timer = null; } } void _schedule({DateTime? current}) { _timer?.cancel(); final instant = widget.instant; if (instant == null) return; final now = current ?? widget.now ?? DateTime.now(); _now = now; final next = _nextBoundary(instant, now); final delay = next.difference(now); _timer = Timer(delay.isNegative ? Duration.zero : delay, () { if (!mounted) return; _now = _now.add(delay); setState(() {}); _schedule(current: _now); }); } DateTime _nextBoundary(DateTime instant, DateTime now) { final difference = now.difference(instant); final age = difference.abs(); final unit = age < const Duration(hours: 1) ? const Duration(minutes: 1) : age < const Duration(days: 1) ? const Duration(hours: 1) : age < const Duration(days: 7) ? const Duration(days: 1) : null; if (unit != null) { final units = age.inMilliseconds ~/ unit.inMilliseconds; final boundary = difference.isNegative // Future labels use a decreasing count. Add a second so an exact // boundary does not immediately schedule another zero-delay timer. ? instant.subtract(unit * units).add(const Duration(seconds: 1)) : instant.add(unit * (units + 1)); if (boundary.isAfter(now)) return boundary; } final midnight = DateTime(now.year, now.month, now.day + 1); return midnight.isAfter(now) ? midnight : now.add(const Duration(minutes: 1)); } @override Widget build(BuildContext context) { // The row's time style (an unread row's accent) stays on the label // itself, as on the plain Text this replaces. return Text( formatRelativeTime(widget.instant, now: _now) ?? '', style: DefaultTextStyle.of(context).style, ); } @override void dispose() { _timer?.cancel(); WidgetsBinding.instance.removeObserver(this); super.dispose(); } }