getVelocityEstimate method

  1. @override
VelocityEstimate getVelocityEstimate()
override

Returns an estimate of the velocity of the object being tracked by the tracker given the current information available to the tracker.

Information is added using addPosition.

Returns null if there is no data on which to base an estimate.

Implementation

@override
VelocityEstimate getVelocityEstimate() {
  // Has user recently moved since last sample?
  if (_sinceLastSample.elapsedMilliseconds > VelocityTracker._assumePointerMoveStoppedMilliseconds) {
    return const VelocityEstimate(
      pixelsPerSecond: Offset.zero,
      confidence: 1.0,
      duration: Duration.zero,
      offset: Offset.zero,
    );
  }

  // The velocity estimated using this expression is an approximation of the
  // scroll velocity of an iOS scroll view at the moment the user touch was
  // released, not the final velocity of the iOS pan gesture recognizer
  // installed on the scroll view would report. Typically in an iOS scroll
  // view the velocity values are different between the two, because the
  // scroll view usually slows down when the touch is released.
  final Offset estimatedVelocity = _previousVelocityAt(-2) * 0.6
                                 + _previousVelocityAt(-1) * 0.35
                                 + _previousVelocityAt(0) * 0.05;

  final _PointAtTime? newestSample = _touchSamples[_index];
  _PointAtTime? oldestNonNullSample;

  for (int i = 1; i <= _sampleSize; i += 1) {
    oldestNonNullSample = _touchSamples[(_index + i) % _sampleSize];
    if (oldestNonNullSample != null) {
      break;
    }
  }

  if (oldestNonNullSample == null || newestSample == null) {
    assert(false, 'There must be at least 1 point in _touchSamples: $_touchSamples');
    return const VelocityEstimate(
      pixelsPerSecond: Offset.zero,
      confidence: 0.0,
      duration: Duration.zero,
      offset: Offset.zero,
    );
  } else {
    return VelocityEstimate(
      pixelsPerSecond: estimatedVelocity,
      confidence: 1.0,
      duration: newestSample.time - oldestNonNullSample.time,
      offset: newestSample.point - oldestNonNullSample.point,
    );
  }
}