Files
pipelines/app/lib/ui/text/live_elapsed_builder.dart
T
alan 7ff012880b Add explicit surface visibility signal
Provide composable shown/current visibility for retained surfaces and migrate visibility readers away from TickerMode. This keeps ticker muting separate from painted and current-surface state.
2026-11-10 20:28:09 +00:00

85 lines
2.0 KiB
Dart

import 'package:flutter/widgets.dart';
import 'elapsed_clock.dart';
import '../motion/surface_visibility.dart';
/// Builds a running item's elapsed-time text from the [ElapsedClock], and
/// rebuilds only itself as that duration advances.
///
/// With a null [since] (nothing running) it builds once from the clock's time
/// and watches nothing, so no timer runs. While its tickers are muted (an
/// offstage tab or a covered route) it stops watching and catches up when
/// shown again.
class LiveElapsedBuilder extends StatefulWidget {
const LiveElapsedBuilder({
super.key,
required this.since,
required this.builder,
});
/// When the running item started; null when it is not running.
final DateTime? since;
/// Builds the text for the clock's current time.
final Widget Function(BuildContext context, DateTime now) builder;
@override
State<LiveElapsedBuilder> createState() => _LiveElapsedBuilderState();
}
class _LiveElapsedBuilderState extends State<LiveElapsedBuilder> {
ElapsedClock? _clock;
bool _shown = true;
bool _watching = false;
@override
void didChangeDependencies() {
super.didChangeDependencies();
final clock = ElapsedClockScope.of(context);
if (clock != _clock) {
_unwatch();
_clock = clock;
}
_shown = SurfaceVisibility.shownOf(context);
_sync();
}
@override
void didUpdateWidget(LiveElapsedBuilder oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.since != widget.since) {
_unwatch();
_sync();
}
}
void _sync() {
final since = widget.since;
if (since == null || !_shown) {
_unwatch();
} else if (!_watching) {
_clock!.watch(this, since, _tick);
_watching = true;
}
}
void _unwatch() {
if (!_watching) return;
_clock?.unwatch(this);
_watching = false;
}
void _tick() {
if (mounted) setState(() {});
}
@override
Widget build(BuildContext context) => widget.builder(context, _clock!.now);
@override
void dispose() {
_unwatch();
super.dispose();
}
}