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

查看:259
本文介绍了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());
  },

,然后将Key添加到列表后面的小部件,并使用它来获取小部件矩形左上角的全局位置以及小部件的大小,并使用它们来获取小部件的矩形:

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;

如果背景小部件不移动,则可以使用WidgetsBinding.instance.addPostFrameCallback在下一帧的initState中进行操作(如果在initState中同步进行操作,则渲染对象将为null)并保存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天全站免登陆