Shyam Singh
Shyam Singh

Reputation: 77

Pause the duration of a Ticker

Is there any way to pause a Ticker in Dart/Flutter?

I tried using

Ticker t = Ticker(print);
t.start();
t.muted = true;

This does pause the ticks, but the Stopwatch that could have been implicitly set still seems to continue working. Is there any way to stop it or maybe some efficient workaround if I rely on the duration to perform something like an animation?

Upvotes: 2

Views: 777

Answers (1)

ch271828n
ch271828n

Reputation: 17597

Here is my solution (not fully tested):

EDIT 2: Tested and already used in my project.

import 'package:flutter/scheduler.dart';

typedef void ResumableTickerCallback(Duration duration);

class ResumableTicker {
  final ResumableTickerCallback _callback;

  Ticker _ticker;
  Duration _offset = Duration.zero;
  Duration _lastTickRawDuration = Duration.zero;

  ResumableTicker.fromProvider(TickerProvider vsync, this._callback) {
    _ticker = vsync.createTicker(_tick);
  }

  void _tick(Duration rawDuration) {
    _lastTickRawDuration = rawDuration;
    _callback(_getActualFromTickRawDuration(rawDuration));
  }

  Duration _getActualFromTickRawDuration(Duration rawDuration) => rawDuration + _offset;

  Duration get lastTickDuration => _getActualFromTickRawDuration(_lastTickRawDuration);

  void startOrResume() {
    _ticker.start();
  }

  void pause() {
    _ticker.stop();
    _offset = lastTickDuration;
    _lastTickRawDuration = Duration.zero; // to keep last tick ACTUAL duration unchanged
  }

  void seek(Duration newTime) {
    final delta = newTime - _getActualFromTickRawDuration(_lastTickRawDuration);
    _offset += delta;
    _lastTickRawDuration = newTime - _offset;
  }

  bool get isTicking => _ticker.isTicking;

  void dispose() => _ticker.dispose();
}

Upvotes: 3

Related Questions