其他分享
首页 > 其他分享> > Flutter ScrollView或ListView的子View是否露出显示

Flutter ScrollView或ListView的子View是否露出显示

作者:互联网

GitHub 源码

需求

在类似 ScrollView 的滑动布局中,当某个 子View 露出后进行上报

方法

  1. 给 滑动布局 (ScrollView、ListView)、子View 设置 Key,采用GlobalKey
    • GlobalKey 始于跨组件查询
  2. 根据 key 算出全局坐标、尺寸
  3. 剩下的就是小学算术题了。
    RenderBox scrollViewRenderBox = scrollViewRenderObject;
    /// offset.dy 就是 widget左上角的 y轴坐标
    Offset scrollViewPosition = scrollViewRenderBox.localToGlobal(Offset.zero); 
    /// size就是 widget 的尺寸
    Size scrollViewSize = scrollViewRenderBox.size;

注意

代码

import 'package:flutter/cupertino.dart';

class ListItemExposeManager {
  bool isExpose = false;
  GlobalKey listItemViewKey;
  GlobalKey scrollViewKey;
  Function(bool isExpose) exposeCallback;
  ScrollController scrollViewController;

  /// Be attention, not every widget will mapping to RenderObject, Element.
  /// Sometime the widget is just constraint, Change another widget to set key if RenderObject is null.
  ListItemExposeManager(this.listItemViewKey, this.scrollViewKey,
      this.scrollViewController, this.exposeCallback) {
    scrollViewController.addListener(() => updateStatus());
    WidgetsBinding.instance?.addPostFrameCallback((_) => updateStatus());
  }

  void updateStatus() {
    RenderObject? renderObject =
        listItemViewKey.currentContext?.findRenderObject();
    if (renderObject is! RenderBox) {
      return;
    }
    RenderBox listItemRenderBox = renderObject;
    /// 全局坐标系 坐标
    Offset listItemPosition = listItemRenderBox.localToGlobal(Offset.zero);
    Size listItemSize = listItemRenderBox.size;
    if (listItemPosition == null || listItemSize == null) {
      return;
    }

    RenderObject? scrollViewRenderObject =
        scrollViewKey.currentContext?.findRenderObject();
    if (scrollViewRenderObject is! RenderBox) {
      return;
    }
    RenderBox scrollViewRenderBox = scrollViewRenderObject;
    Offset scrollViewPosition = scrollViewRenderBox.localToGlobal(Offset.zero);
    Size scrollViewSize = scrollViewRenderBox.size;
    if (scrollViewPosition == null || scrollViewSize == null) {
      return;
    }

    double minScrollDy = listItemPosition.dy +
        listItemSize.height -
        scrollViewPosition.dy -
        scrollViewSize.height;

    bool afterListView = minScrollDy > 0;
    bool beforeListView = listItemPosition.dy + listItemSize.height < scrollViewPosition.dy;
    bool currentIsExpose = !beforeListView && !afterListView;

    if (currentIsExpose != isExpose) {
      exposeCallback(currentIsExpose);
    }
    isExpose = currentIsExpose;
  }

}

参考

标签:RenderObject,widget,null,scrollViewRenderBox,dy,ScrollView,Offset,ListView,Flutt
来源: https://blog.csdn.net/zhjali123/article/details/122691372