scrollToPosition method

void scrollToPosition()

Implementation

void scrollToPosition() {
  if (Get.context == null) {
    return;
  }
  MediaQueryData mediaQueryData = MediaQuery.of(Get.context!);

  double position = mediaQueryData.viewInsets.bottom;
  // final double maxScrollExtent = _scrollController.position.maxScrollExtent;
  // final double minScrollExtent = _scrollController.position.minScrollExtent;

  // final double clampedPosition =
  //     position.clamp(minScrollExtent, maxScrollExtent);

  // if (clampedPosition != position) {
  //   print(1);
  //   // 滚动位置超出边界,进行调整
  //   _scrollController.jumpTo(clampedPosition);
  // } else {
  //   print(2);
  // 滚动位置在合法范围内,执行滚动动画

  // 获取页面高度
  var pageHeight = mediaQueryData.size.height;
  if (pageHeight <= 0) {
    return;
  }

  // 获取目标位置的坐标
  RenderBox? renderBox =
      targetWidgetKey.currentContext?.findRenderObject() as RenderBox?;
  if (renderBox == null) {
    return;
  }
  // 转换为全局坐标
  final bottomOffset =
      renderBox.localToGlobal(Offset(0, renderBox.size.height));
  final targetDy = bottomOffset.dy;
  // 获取要滚动的距离
  // 即被软键盘挡住的那段距离 加上 _scrollController.offset 已经滑动过的距离
  final offsetY =
      position - (pageHeight - targetDy) + scrollController.offset;
  // print('------$pageHeight-----$targetDy------$position-----$offsetY');
  // 滑动到指定位置
  if (offsetY > 0) {
    scrollController.animateTo(
      offsetY,
      duration: kTabScrollDuration,
      curve: Curves.ease,
    );
  }

  // _scrollController.animateTo(
  //   position,
  //   duration: const Duration(seconds: 1),
  //   curve: Curves.linear,
  // );
  // }
}