GestureDetector¶
可以响应点击
onTap:没有参数的回调
正常点击:onTapDown --> onTapUp --> onTap
点击后滑动:onTapDown --> onTapCancel
import 'package:flutter/material.dart';
class _GestureDetectorExampleState extends State<GestureDetectorExample> {
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      // 长按
      onLongPressStart: (details) {
        if (mounted) {
          setState(() => globalPosition = details.globalPosition);
        }
      },
      onLongPressMoveUpdate: (details) {
        if (mounted) {
          setState(() => globalPosition = details.globalPosition);
        }
      },
      onLongPressUp: () async {
        await Future.delayed(const Duration(milliseconds: 800)).then((_) {
          if (mounted) {
            setState(() => globalPosition = null);
          }
        });
      },
      // 点击
      onTapDown: (TapDownDetails details) {
        print(
            "onTapDown---${details.globalPosition}---${details.localPosition}");
      },
      onTapUp: (details) {
        print("onTapUp---${details.globalPosition}---${details.localPosition}");
      },
      onTap: () {
        print("onTap");
      },
      onTapCancel: () {
        print("onTapCancel");
      },
      child: Container(
        width: 200,
        height: 200,
        color: Colors.orange,
        alignment: Alignment.center,
        child: const Text(
          "手势",
          style: TextStyle(color: Colors.white, fontSize: 30),
        ),
      ),
    );
  }
}
扩大GestureDetector的点击范围¶
- 使用Padding: 在GestureDetector外部包0裹一个Padding小部件来增加可点击的区域。
Padding(
  padding: EdgeInsets.all(20.0), // 扩大20像素的点击范围
  child: GestureDetector(
    onTap: () {
      print('Tap!');
    },
    child: Container(
      // ...
    ),
  ),
)
- 使用Container并设置margin: 给GestureDetector的子Container设置margin属性,这样点击区域也会相应增大。
GestureDetector(
  onTap: () {
    print('Tap!');
  },
  child: Container(
    margin: EdgeInsets.all(20.0), // 扩大20像素的点击范围
    // ...
  ),
)
- 使用SizedBox或Container设置大小: 如果想要确保GestureDetector有一个最小的点击区域,可以使用SizedBox或者给Container设置一个width和height。
GestureDetector(
  onTap: () {
    print('Tap!');
  },
  child: Container(
    width: 100,
    height: 100,
    // ...
  ),
)
- 使用HitTestBehavior: 如果你的GestureDetector是透明的或者没有子小部件占据空间,你可以通过设置behavior属性来确保它可以接收点击事件。
GestureDetector(
  behavior: HitTestBehavior.opaque, // 现在整个GestureDetector都可以点击
  onTap: () {
    print('Tap!');
  },
  child: Container(
    // 甚至可以没有尺寸
  ),
)