import 'package:flutter/widgets.dart'; /// Scrolls one artifact of a lazy gallery into view. /// /// The gallery builds only the rows on screen, so a requested artifact far /// down a run may not exist yet. [reveal] scrolls by most of a viewport each /// frame until the row keyed by [target] is built, then centres it. It stops /// at the end of the list either way and always reports [onDone] exactly once. class ArtifactVisitReveal { /// Wraps the requested row so its position can be found once it is built. final GlobalKey target = GlobalKey(debugLabel: 'artifact-reveal-target'); /// Any widget that is always built inside the gallery's scroll view. final GlobalKey anchor = GlobalKey(debugLabel: 'artifact-reveal-anchor'); int _generation = 0; /// Abandons a reveal in progress (a new request, or the list going away). void cancel() => _generation++; void reveal(VoidCallback onDone) { final generation = ++_generation; // Generous for any recorded run, yet bounded so a row that never builds // cannot keep scheduling frames. var remaining = 200; void step() { if (generation != _generation) return; final row = target.currentContext; if (row != null && row.mounted) { Scrollable.ensureVisible(row, alignment: 0.5); onDone(); return; } final anchorContext = anchor.currentContext; final position = anchorContext == null ? null : Scrollable.maybeOf(anchorContext)?.position; if (position == null || !position.hasContentDimensions || position.pixels >= position.maxScrollExtent || --remaining <= 0) { onDone(); return; } position.jumpTo( (position.pixels + position.viewportDimension * 0.8).clamp( position.minScrollExtent, position.maxScrollExtent, ), ); WidgetsBinding.instance.addPostFrameCallback((_) => step()); WidgetsBinding.instance.scheduleFrame(); } WidgetsBinding.instance.addPostFrameCallback((_) => step()); WidgetsBinding.instance.scheduleFrame(); } }