如何使可点击的小部件在flutter堆栈后面



出于某些目的,我在堆栈中有两个scaffold小部件。每个scaffold都有自己的内容。第二个支架具有透明的背景色,因此第一个支架是可见的。

Stack(
children: [
Scaffold(
body: GestureDetector(
onTap: () {},
child: myBody(),
),
),
Scaffold(
backgroundColor: Colors.transparent,
body: ListView.builder(
itemBuilder: (context, index) => ...,
),
)
],
),

第一个Scaffold中的GestureDetector不起作用,这是因为Scaffold堆栈

注意:我不能包装第二个ScaffoldIgnorePointer,因为它有可点击的ListView。它会忽略任何指针

如何解决这个问题×_O

可以从第二个scaffold列表项点击中获取回调方法。并创建一个将在第一个scaffoldGestureDetector上提供的级别上的函数。

void main(List<String> args) {
Widget myBody() {
return Container(
color: Colors.cyanAccent.withOpacity(.3),
);
}
void topLevelGesture() {
debugPrint("got hit on GestureDetector");
}
runApp(
MaterialApp(
home: Stack(
children: [
Scaffold(
body: GestureDetector(
onTap: topLevelGesture,
child: myBody(),
),
),
Scaffold(
backgroundColor: Colors.transparent,
body: ListView.builder(
itemBuilder: (context, index) => ListTile(
title: Text("item $index"),
onTap: () {
topLevelGesture();
print("tapped $index");
},
),
),
),
],
),
),
);
}

你可以将Gesture设置为堆栈外部,使用这个内部列表,click也可以工作,但是当你将第一个Scaffold主体设置为可点击时,它就不起作用了,因为第二个Scaffold覆盖了它。

GestureDetector(
onTap(){}
child:Stack(
children[
Scaffold(
body:   myBody()

)
Scaffold(
backGroundColor: Colors.transparent
body: ListView.bulder(){....}
)
]
))

您需要在堆栈小部件的末尾添加可点击小部件,如下所示:

Stack(
children[
firstWidget(),
GestureDetector(
onTap(){},
child:  secondWidget()
)

]
)

就像这样用IgnorePointer代替secondWidget(),firstWidget()也可以点击。

Stack(
children[
firstWidget(),
IgnorePointer(
child: secondWidget(),
),
]
)

最新更新