首页 > 解决方案 > 在我的颜色选择器上结束拖动后如何获取数据?

问题描述

现在,每次我拖动我的选择器颜色都会改变。我不想每次都触发事件。结束后,我想获得颜色代码..

return GestureDetector(
  onPanDown: (details) => handleTouch(details.globalPosition, context),
  onPanStart: (details) => handleTouch(details.globalPosition, context),
  onPanUpdate: (details) => handleTouch(details.globalPosition, context),
  child: Stack(children: [frame, content, thumb]),
);


  /// calculate colors picked from palette and update our states.
  void handleTouch(Offset globalPosition, BuildContext context) {
    RenderBox box = context.findRenderObject();
    Offset localPosition = box.globalToLocal(globalPosition);
    double percent;
    if (widget.horizontal) {
      percent = (localPosition.dx - widget.thumbRadius) / barWidth;
    } else {
      percent = (localPosition.dy - widget.thumbRadius) / barHeight;
    }
    percent = min(max(0.0, percent), 1.0);
    setState(() {
      this.percent = percent;
    });
    switch (widget.pickMode) {
      case PickMode.Color:
        Color color = HSVColor.fromAHSV(1.0, percent * 360, 1.0, 1.0).toColor();
        widget.colorListener(color.value);
        break;
      case PickMode.Grey:
        final int channel = (0xff * percent).toInt();
        widget.colorListener(Color
          .fromARGB(0xff, channel, channel, channel)
          .value);
        break;
    }
  }

试过 panEnd 不工作

onPanEnd: (end) => handleTouch(end.velocity.pixelsPerSecond,context),

完整代码https://github.com/Cricin/ColorPicker-flutter/blob/master/lib/color_picker.dart

标签: flutterdart

解决方案


什么地方出了错

onPanDown: (details) => handleTouch(details.globalPosition, context),
onPanStart: (details) => handleTouch(details.globalPosition, context),
onPanUpdate: (details) => handleTouch(details.globalPosition, context),

尝试删除以下一些不适合您所需行为的拖动回调。

深入了解回调

onPanStart

/// A pointer has contacted the screen with a primary button and has begun to
/// move.
///
/// See also:
///
///  * [kPrimaryButton], the button this callback responds to.
final GestureDragStartCallback onPanStart;

onPanUpdate

/// A pointer that is in contact with the screen with a primary button and
/// moving has moved again.
///
/// See also:
///
///  * [kPrimaryButton], the button this callback responds to.
final GestureDragUpdateCallback onPanUpdate;

现在你可以使用 onPanDown

return GestureDetector(
  // Might worth noting, review the behavior of your choice onPanDown onPanEnd
  onPanDown: (details) => handleTouch(details.globalPosition, context),
  // Depends if you still need this.
  // onPanStart: (details) => handleTouch(details.globalPosition, context),
  child: Stack(children: [frame, content, thumb]),
);

推荐阅读