gpt4 book ai didi

Flutter - 点击/触摸区域如何工作?

转载 作者:行者123 更新时间:2023-12-04 00:23:53 32 4
gpt4 key购买 nike

1) 如果我有这个,当我点击子 Container 时它不会打印'tap':

Container(
color: Colors.red,
child: GestureDetector(
onTap: () => print('tap'),
child: Container(
width: 100,
height: 100,
),
),
),

2) 如果我有这个,当我点击子 Container 时,它会打印“tap”:

Container(
color: Colors.red,
child: GestureDetector(
onTap: () => print('tap'),
child: Container(
width: 100,
height: 100,
decoration: BoxDecoration(),
),
),
),

3) 如果我有这个,当我在文本之外点击子 Container 时,它会打印“tap”:

Container(
color: Colors.red,
child: GestureDetector(
onTap: () => print('tap'),
child: Container(
width: 100,
height: 100,
child: Text("A"),
),
),
),

谁能解释一下这三种行为?

最佳答案

  1. 一个 Container有界(height and width)只不过是其他小部件进入其中的占位符。由于您没有提供任何child给它或任何其他属性(property),例如 colordecoration对它来说,container GestureDetector 被认为是不可见的.

据官方GestureDetector文件,by default a GestureDetector with an invisible child ignores touches. this behavior can be controlled with behavior.

如果您仍然想要占位符 container要被识别为点击事件,请使用 behavior GestureDetector 的属性(property),这将告诉 GestureDetector 点击容器,然后您将看到 tap打印出来,如下:

Container(
color: Colors.red,
child: GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () => print('tap'),
child: Container(
width: 100,
height: 100,
),
),
),
  1. 在这种情况下,由于您提供了 decoration属性(property)和使用BoxDecoration() ,它根据其父小部件提供的边界呈现一个框。所以,container有一个盒子的形状。为了查看盒子形状在容器内是如何呈现的,只需提供 border属性,如下:
Container(
color: Colors.red,
child: GestureDetector(
onTap: () => print('tap'),
child: Container(
width: 100,
height: 100,
decoration: BoxDecoration(
border: Border.all(color: Colors.yellow, width: 4)
),
),

enter image description here

你可以看到yellow跨越整个 container 的边界大小,作为 container 之上的一层现在被认为是可点击的。因此,GestureDetector 的点击被识别,您会看到 tap打印出来的。

  1. 在这种情况下,由于您提供了 child小部件为 text , GestureDetector识别它,因为小部件是可见的,因此 tap被打印,无论您是点击文本还是文本之外,因为因为 GestureDetector它本身没有大小,它依赖于 child 的大小,在这种情况下是 bounds (高度和宽度)。因此,它认为整个有界区域都是可点击的,你会得到 tap事件打印在其中的任何位置。

希望这能回答你的问题。

关于Flutter - 点击/触摸区域如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58533826/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com