我有一个里面的按钮GestureDetector
。theGestureDetector
和 theIconButton
都有自己的功能。但是,我只想GestureDetector
在点击图标时执行而不是 ```IconButton`` 的功能。我知道这个问题的一些解决方案,但我仍然想知道在上述情况下,是否有任何解决方案可以防止颤振执行 IconButton 的功能?
谢谢
我有一个里面的按钮GestureDetector
。theGestureDetector
和 theIconButton
都有自己的功能。但是,我只想GestureDetector
在点击图标时执行而不是 ```IconButton`` 的功能。我知道这个问题的一些解决方案,但我仍然想知道在上述情况下,是否有任何解决方案可以防止颤振执行 IconButton 的功能?
谢谢
点击优先子> GesuterDetector。如果您有一个孩子,则只有IconButton
on会起作用。GestureDetector
IconButton
假设您有一个列。
onPressed
。IconButton
AbsorbPointer
将阻止其子项的点击事件,并且GestureDetector
在这种情况下点击事件将起作用。IgnorePointer
将完全忽略其区域内的任何点击事件。演示小部件
class MyStatefulWidget extends StatefulWidget {
const MyStatefulWidget();
// final String title;
@override
State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
bool _disableIconButton = false;
@override
Widget build(BuildContext context) {
return new Scaffold(
backgroundColor: Colors.white,
body: Container(
child: Column(
children: [
GestureDetector(
onTap: () {
print("GestureDetector Tapped");
},
child: IconButton(
onPressed: () {
print(" only Icon will be working here");
},
icon: Icon(Icons.ac_unit),
),
),
SizedBox(
height: 100,
),
GestureDetector(
onTap: () {
print("GestureDetector Tapped");
},
child: Column(
children: [
Text("Inside Column"),
Switch(
value: _disableIconButton,
onChanged: (v) {
setState(() {
_disableIconButton = v;
});
},
),
///* Colors will faded on
IconButton(
onPressed: _disableIconButton
? null
: () {
print("Icon null checker tapped");
},
icon: Icon(Icons.ac_unit),
),
///* Colors will faded on like disable and will work on GuesterTap
AbsorbPointer(
absorbing: _disableIconButton,
child: IconButton(
onPressed: _disableIconButton
? null
: () {
print("Icon AbsorbPointer tapped");
},
icon: Icon(Icons.ac_unit),
),
),
///* it will ignore tap event
IgnorePointer(
ignoring: _disableIconButton,
child: IconButton(
onPressed: _disableIconButton
? null
: () {
print("Icon IgnorePointer tapped");
},
icon: Icon(Icons.ac_unit),
),
),
],
),
)
],
),
),
);
}
}
Solution 2: Write a separate function and pass a parameter to trigger that function based on your requirement.
对这个。我认为他的意思是,如果用户点击图标/按钮,您现在可以调用 2 个功能:
tapIcon() {//do this and that}
tapButton() {//do this and that}
然后你创建一个第三个函数,它有一个参数,你决定应该调用哪个函数:
callFunc(bool iconTap) {
iconTap ? tapIcon() : tapButton();
}
你在 onTap/onPressed 上使用它:() {callFunc(true/false);}
或者,如果您打算拥有更多功能,则可以使用 enum:
enum FunctionsEnum { BUTTON, ICON }
callFunc(FunctionsEnum functionsEnum) {
if (functionsEnum == FunctionsEnum.BUTTON) tapButton();
if (functionsEnum == FunctionsEnum.ICON) tapIcon();
}
然后传递一个枚举:onTap: () {callFunc(FunctionsEnum.BUTTON);}
解决方案 1:您可以只提供一个空函数到IconButton onPressed method
.
解决方案2:编写一个单独的函数并传递一个参数以根据您的要求触发该函数。