Flutter:如何使 ListView 对指针事件透明(但不是它的非透明内容)? [英] Flutter: How to make a ListView transparent to pointer events (but not its non-transparent contents)?

查看:13
本文介绍了Flutter:如何使 ListView 对指针事件透明(但不是它的非透明内容)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Scrollable(ListView 或任何其他),它包含一个透明小部件,例如 Container(height:200).我可以通过小部件和可滚动查看(换句话说,我可以看到可滚动后面的小部件).

I have a Scrollable (ListView or any other) and it contains a transparent widget, say Container(height:200). I can see through both the widget and the scrollable (in other words I can see the widgets behind the scrollable).

我怎样才能点击透明小部件和可滚动小部件,以便到达可滚动小部件后面的小部件?

How can I be able to click through the transparent widget and the scrollable, so that I reach the widgets behind the scrollable?

ListView(
  children: [
    Container(height: 200), // Transparent.
    Container(color: Colors.red, height: 200),
    ],
);

注意,我不能用 IgnorePointer 包裹滚动条,因为我仍然想点击滚动条中不透明的小部件.

Note, I cannot wrap the scrollable with IgnorePointer, because I still want to click the non-transparent widgets in the scrollable.

推荐答案

我能想到的唯一合理的解决方案是在透明容器上有一个GestureDetector,它会给你全局位置水龙头:

The only reasonable solution I can think of is to have a GestureDetector on the transparent container, which will give you the global position of the taps:

GestureDetector(
  onTapUp: (TapUpDetails tapUpDetails) {
    print("onTapUp global: " + tapUpDetails.globalPosition.toString());
  },

然后给list后面的widget添加一个Key,并用它来获取widget的矩形左上角的全局位置,以及widget的大小,以及使用这些来获取小部件的矩形:

And then add a Key to the widget behind the list, and use it to get the global position of the top left corner of the widget's rectangle, as well as the size of the widget, and use those to get the rectangle of the widget:

RenderBox renderBox = _key.currentContext.findRenderObject();
Offset topLeftCorner = renderBox.localToGlobal(Offset.zero);
Size size = renderBox.size;
Rect rectangle = topLeftCorner & size;

如果背景小部件不移动,您可以在下一帧的 initState 内使用 WidgetsBinding.instance.addPostFrameCallback 执行此操作(如果在 initState 中同步执行它并保存 Rect - 否则您将不得不在每次点击时重新计算它.

If the background widget does not move, you can do it within initState on the very next frame using WidgetsBinding.instance.addPostFrameCallback (the render object will be null if do it synchronously within initState) and save the Rect - otherwise you will have to recalculate it on every tap.

最后在透明容器上的每一次点击都可以计算出点击的位置是否在背景小部件的边界内,并调用相应的代码:

And then finally on each tap on the transparent container you can calculate whether the tap's position is within the boundaries of the background widget, and invoke the corresponding code:

// if tap is within boundaries of the background widget
if (rectangle.contains(tapUpDetails.globalPosition)) {
  // your code here
}

这篇关于Flutter:如何使 ListView 对指针事件透明(但不是它的非透明内容)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆