一直在开发一个 flutter 应用程序并根据一些 Firebase 数据动态构建一些容器。 我想知道是否有办法获得容器的 onTap 方法(或任何不是按钮的小部件?
这是一个代码示例:
child: new Container(
//INSERT ONTAP OR ONPRESSED METHOD HERE
margin: const EdgeInsets.symmetric(vertical: 10.0),
child: new Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
new Container(
margin: const EdgeInsets.only(right: 16.0),
child: new GoogleUserCircleAvatar(snapshot.value['images'][0]),
),
new Column(
crossAxisAlignment: CrossAxisAlignment.start,
children : [
new Container(
padding: const EdgeInsets.only(bottom: 8.0),
child: new Text("${snapshot.value['name']}",
style: new TextStyle(
fontWeight: FontWeight.bold,
),
),
),
new Text("${snapshot.value['description']}",
style: new TextStyle(
color: Colors.grey[500],
),
),
]
)
],
),
您可以将
Container
包裹在 InkWell
或 GestureDetector
中。
InkWell: 用于具有波纹效果的可点击区域(Material Design 触摸指示器)。 GestureDetector: 适用于没有视觉提示的一般点击。
您可以将容器包装在 Inkwell() 或 GestureDetector() 中,如下所示
InkWell(
child: Container(...),
onTap: () {
print("tapped on container");
},
);
使用手势检测器
GestureDetector(
onTap: () { print("Container was tapped"); },
child: Container(...),
)
两者之间的唯一区别是,当指针与屏幕接触时,InkWell 会提供波纹效果,而 GestureDetector 则没有这样的视觉反馈。
截图:
您可以同时使用
GestureDetector
和 InkWell
,但我建议您使用 InkWell
,因为它可以显示 GestureDetector
无法显示的连锁反应。
GestureDetector
和InkWell
之间的区别:
两者有许多共同点,如
onTap
、 onLongPress
等。主要区别在于GestureDetector
有更多的控件,如拖动等。另一方面,InkWell
提供了一些不错的连锁反应。
您可以根据需要使用其中任何一个。如果您想要涟漪效果,请选择
InkWell
,如果您需要更多控件,请选择 GestureDetector
,甚至将两者结合起来。
Material(
color: Colors.blue, // Background color
child: InkWell(
splashColor: Colors.grey, // Splash color
onTap: () => print("Container pressed"), // Handle your onTap here.
child: Container(height: 200, width: 200),
),
)
除了其他人在答案中所说的之外,如果您在
Card
中使用InkWell
,那么InkWell
将隐藏Android上的涟漪效果 - 您可以看到它发生在后台,但看不到卡本身。
解决方案是在
InkWell
内创建一个 Card
。
return Card(
child: InkWell(
child: Row(
// Row content
),
onTap: () => {
print("Card tapped.");
},
),
elevation: 2,
);
这将帮助您获得涟漪效果并在 Android 上执行点击捕获。