处理点击

捕获和处理点击动作

实用教程chevron_right手势操作 (Gestures)chevron_right捕获和处理点击动作

我们的 app 不仅要把信息展示给用户,还要和用户进行交互。怎么响应用户的点击,拖动等操作行为呢? ——使用 GestureDetector Widget。

info提示

了解更多,请参考下方「每周 Widget」的里关于 GestureDetector 的短视频:

GestureDetector | Flutter widget of the week

你可以通过以下步骤来实现一个按钮,当用户点击的时候显示 snackbar 消息:

  1. 创建一个按钮。
  2. GestureDetector 包裹按钮,并传入 onTap 回调函数。

dart

// The GestureDetector wraps the button.
GestureDetector(
  // When the child is tapped, show a snackbar.
  onTap: () {
    const snackBar = SnackBar(content: Text('Tap'));

    ScaffoldMessenger.of(context).showSnackBar(snackBar);
  },
  // The custom button
  child: Container(
    padding: const EdgeInsets.all(12),
    decoration: BoxDecoration(
      color: Colors.lightBlue,
      borderRadius: BorderRadius.circular(8),
    ),
    child: const Text('My Button'),
  ),
)

content_copy

注意

#

  1. 如果你想添加点按涟漪效果 (Material Design) 请参考文章 添加点按涟漪效果 (Material Design)
  2. 这里为了说明原理,我们创建了自定义的按钮,其实 Flutter 已经为我们准备了很多现成的按钮供我们使用,比如: ElevatedButtonTextButtonCupertinoButton

交互式样例

#

posted on 2024-12-10 09:29  AtlasLapetos  阅读(13)  评论(0)    收藏  举报