scrollUntilVisibleFinder method

Future<void> scrollUntilVisibleFinder(
  1. Finder finder, {
  2. String? scrollableId,
  3. int? timeoutMs,
})

Implementation

Future<void> scrollUntilVisibleFinder(
  Finder finder, {
  String? scrollableId,
  int? timeoutMs,
}) async {
  final effectiveTimeout =
      timeoutMs ?? config.defaultWaitTimeout.inMilliseconds;
  final scrollable = await scrollableWaiter.wait(
    scrollableId: scrollableId,
    timeoutMs: effectiveTimeout,
  );

  // Flutter's scrollUntilVisible always performs up to 50 drags, even when
  // the target is absent and the scrollable has already reached its extent.
  // Apart from ignoring the caller's timeout, that produces a warning for
  // every drag when the viewport is covered or cannot receive a gesture.
  // Drive the scrollable only while it is making progress, then report the
  // actual unresolved target instead of leaking StateError: No element.
  await tester.pump(Duration.zero);
  var attempts = 0;
  final maxAttempts = (effectiveTimeout ~/ 50).clamp(1, 50);
  final scrollableState = tester.state<ScrollableState>(scrollable);
  while (!assertions.hasVisibleElement(finder) && attempts < maxAttempts) {
    final position = scrollableState.position;
    if (!position.hasContentDimensions || position.extentAfter <= 0) break;

    final previousPixels = position.pixels;
    await tester.drag(
      scrollable,
      const Offset(0, -300),
      warnIfMissed: false,
    );
    await tester.pump(const Duration(milliseconds: 50));
    attempts++;

    if ((scrollableState.position.pixels - previousPixels).abs() < 0.5) {
      break;
    }
  }
  if (!assertions.hasVisibleElement(finder)) {
    throw EnsembleTestFailure(
      'scrollUntilVisible: no visible widget matched $finder after '
      '$attempts scroll attempts (scrollable: $scrollable).',
    );
  }
  await runtime.settleAfterAction();
}