rendering

Automatically scroll to the top to align with the container when components are not visible in the Leading direction of the container

Automatically scroll to the bottom and container alignment when the component is not visible in the Trailing direction of the scroll container

Do not scroll when the component is fully visible

Code implementation

void _makeVisible() {
  ///_visibleKey is of GlobalKey type and is bound to the test component
  var object = _visibleKey.currentContext.findRenderObject();
  var position = Scrollable.of(_visibleKey.currentContext).position;
  final RenderAbstractViewport viewport = RenderAbstractViewport.of(object);
  double max = viewport
    .getOffsetToReveal(object, 0.0)
    .offset
    .clamp(position.minScrollExtent, position.maxScrollExtent) as double;
  double min = viewport
    .getOffsetToReveal(object, 1.0)
    .offset
    .clamp(position.minScrollExtent, position.maxScrollExtent) as double;
  if (position.pixels >= min && position.pixels <= max) {
    Scaffold.of(_visibleKey.currentContext)
      .showSnackBar(SnackBar(content: Text("No scrolling")));
    return;
  }
  ///Scroll until fully visible
  position.jumpTo(position.pixels.clamp(min, max));
}
Copy the code

Analysis:

  • Either the ListView or the CustomScrollView will eventually generate widgets of type Scrollable

  • The Scrollable component will eventually generate a Viewport or ShrinkWrapViewport component

  • The Viewport class component generates a RenderObject of type RenderViewport, which is a subtype of RenderAbstractViewport

RenderAbstractViewport. GetOffsetToReveal (RenderObject object, double alignment) methods:

  • An alignment of 0.0 indicates object andThe top containerAlign the distance TOP to scroll
  • An alignment of 0.5 indicates that the object and the container are aligned to the CENTER of the distance to be rolled
  • An alignment of 1.0 indicates object andAt the bottom of the containerAlign the distance BOTTOM needed to scroll

Pixels: pixels <CENTER<TOP, p =

  • If p is currently less than BOTTOM it is below the container and not completely visible
  • If P is greater than TOP, it is above the container and not completely visible
  • If p is completely visible between BOTTOM and TOP

This code was copied from the scrollable.ensureVisible () method