Flutter - 不用抬起手指进行多个手势操作

10

我想实现以下效果:当用户长按空白屏幕时,一个矩形会出现。在不松开手指的情况下,我希望用户能够拖动矩形的一条边(例如垂直方向)。

我可以分别实现这些效果(长按、释放、拖动),但我需要在不松开手指的情况下完成它们。

目前,我的代码如下:

 @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onPanStart: startDrag,
      onPanUpdate: onDrag,
      onPanEnd: endDrag,
      child: CustomPaint(
        painter: BoxPainter(
          color: BOX_COLOR,
          boxPosition: boxPosition,
          boxPositionOnStart: boxPositionOnStart ?? boxPosition,
          touchPoint: point,
        ),
        child: Container(),
      ),
    );
  }

这实现了边缘拖动,基于这个教程

为了使元素在长时间按压时出现,我使用了一个Opacity小部件。

@override
  Widget build(BuildContext context) {
    return new GestureDetector(
      onLongPress: () {
        setState(() {
          this.opacity = 1.0;
        });
      },
      child: new Container(
        width: width,
        height: height,
        child: new Opacity(
          opacity: opacity,
          child: PhysicsBox(
            boxPosition: 0.5,
          ),
        ),
      ),
    );
  }
1个回答

10
如果还有人感兴趣的话,我能够使用 DelayedMultiDragGestureRecognizer 类实现所需的行为。
代码如下:
  void onDrag(details) {
    // Called on drag update
  }

  void onEndDrag(details) {
    // Called on drag end
  }

  @override
  Widget build(BuildContext context) {
    return new RawGestureDetector(
      gestures: <Type, GestureRecognizerFactory>{
        DelayedMultiDragGestureRecognizer:
            new GestureRecognizerFactoryWithHandlers<
                DelayedMultiDragGestureRecognizer>(
          () => new DelayedMultiDragGestureRecognizer(),
          (DelayedMultiDragGestureRecognizer instance) {
            instance
              ..onStart = (Offset offset) {
                /* More code here */
                return new ItemDrag(onDrag, endDrag);
              };
          },
        ),
      },
    );
  }

ItemDrag 是一个继承自 Flutter Drag 类的类:

class ItemDrag extends Drag {
  final GestureDragUpdateCallback onUpdate;
  final GestureDragEndCallback onEnd;

  ItemDrag(this.onUpdate, this.onEnd);

  @override
  void update(DragUpdateDetails details) {
    super.update(details);
    onUpdate(details);
  }

  @override
  void end(DragEndDetails details) {
    super.end(details);
    onEnd(details);
  }
}

我可以知道onDrag和endDrag是从哪里来的吗? - Kenneth John
谢谢,这正是我所需要的。我想知道为什么Flutter没有类似这样的开箱即用功能。 - Pavel Shorokhov
@KennethJohn,非常抱歉让你等待了这么久。这段代码是几年前为大学项目编写的,所以我无法提供太多帮助,因为我记得不多了。但是,如果有用的话,我找到了其余的代码:https://pastebin.com/bB1gAnWs - David
知识永远不会消失!开个玩笑,看看文档,你就可以开始使用类似以下的代码: onDrag(DragUpdateDetails d) { print('当前位置 ${d.localPosition}'); } endDrag(DragEndDetails d) { print('结束 $d'); } - Matt Takao

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接