首页 > 解决方案 > 如何使用 GestureDetect 在 Flutter 中点击 CustomPaint 路径?

问题描述

我对颤动非常陌生,正在尝试弄清楚如何在 CustomPaint 路径上检测到手势。由于某种原因,我可以点击许多其他东西,但不能点击路径......我如何让它工作?到目前为止,我的代码如下。

import 'package:flutter/material.dart';

void main() => runApp(MbiraShapes());

class MbiraShapes extends StatefulWidget {
    @override
  _MbiraShapesState createState() => _MbiraShapesState();
}

class _MbiraShapesState extends State<MbiraShapes>{

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: 'Mbira Shapes',
        home: PathExample());
  }
}

class PathExample extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return CustomPaint(
      painter: KeyPathPainter(),
    );
  }
}

class KeyPathPainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    Paint lineDrawer = Paint()
      ..color = Colors.blue
      ..strokeWidth = 8.0;

    Path path = Path()
// Moves to starting point
      ..moveTo(50, 50)
      //draw lines passing through xc, yc to end at x,y
      ..quadraticBezierTo(77, 370, 50, 750)
      ..quadraticBezierTo(100, 775, 150, 750)
      ..quadraticBezierTo(110, 440, 75, 50);
    //close shape from last point
    path.close();
    canvas.drawPath(path, lineDrawer);

    Path path2 = Path()
// Moves to starting point
      ..moveTo(250, 50)
      //draw lines passing through xc, yc to end at x,y
      ..quadraticBezierTo(280, 350, 270, 675)
      ..quadraticBezierTo(290, 750, 350, 750)
      ..quadraticBezierTo(365, 710, 345, 600)
      ..quadraticBezierTo(320, 450, 270, 50);
    //close shape from last point
    path2.close();
    canvas.drawPath(path2, lineDrawer);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) => true;
}

我用 GestureDetector 尝试了下面的代码段,但它不起作用。我尝试了一个侦听器,但对 onPointerDown 没有响应,仅针对 onPointerMove,但我需要一个点击动作,而不是移动动作。

@override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(
  
        title: Text("widget.title)"),
      ),
      
      body: Center(
        child: GestureDetector(
          child: CustomPaint(
            painter: KeyPathPainter(),
            child: Container()),
          onTap: () {
            print("tapped the key");
          },
        ),
      ),
    );
  }

我只想点击一个键并得到响应,最终会发出声音,但现在,我只是想弄清楚如何让 onTap 工作。

标签: flutterdartpathgesturedetectorcustom-painting

解决方案


你必须重写hitTest()你的KeyPathPainter类的方法:

@override
bool hitTest(Offset position) {
    // _path - is the same one we built in paint() method;
    return _path.contains(position);
}

这将允许GestureDetector检测路径内的水龙头而不是整个CustomPaint容器。虽然_path必须关闭,因为没有办法——至少我知道——在曲线上测试命中。


推荐阅读