Flutter AnimationController Listender不触发

时间:2019-12-25 21:44:13

标签: flutter dart flutter-animation

我试图在我的Bloc中使用AnimationController每隔几秒钟将一系列图像发送到有状态小部件。以下代码段显示了设置。尽管触发了动画自动收报器(我可以通过自动收报器打印语句看到),但侦听器从不执行。

有什么想法吗?

 class RaspDataBloc extends Bloc<RaspDataEvent, RaspDataState>
    implements TickerProvider {
   ...
    void startImageAnimation() {
    _forecastImageAnimationController = AnimationController(
        value: 0,
        duration: Duration(milliseconds: 15000),
        lowerBound: 0,
        upperBound: _forecastTimes.length.toDouble(),
        vsync: this)
      ..repeat()
      ..addListener(() {
        _postForecastImageSet(_forecastImageAnimationController.value);  <<< doesn't execute
      });
    _forecastImageAnimationController.forward();
  }

  @override
  Ticker createTicker(onTick) {       <<<< This executes
    print('Creating Ticker');
    return Ticker(tickerDuration);
  }

  tickerDuration(Duration elapsed) {
    print('Ticker duration:  $elapsed.inMilliseconds'); <<<< This fires regularly as expected
  }

  Stream<RaspDataState> _postForecastImageSet(double value) async* {
    print("Animation value: $_forecastImageAnimationController.value");
    var imageIndex = value.toInt();
    if (imageIndex < _imageSets.length) {
      print("Posting imageSet[$imageIndex]");
      yield new RaspForecastImageDisplay(_imageSets[imageIndex]);
    }
  }

2 个答案:

答案 0 :(得分:0)

您使用TickerProvider的原因是否特殊?通常,在AnimationController中使用SingleTickerProviderStateMixin。如果这样做,并在initState中创建了动画控制器之后添加了侦听器,则侦听器将起作用。像这样:

class _MyStatefulWidgetState extends State<MyStatefulWidget> with SingleTickerProviderStateMixin {

  AnimationController _animationController;

  @override
  initState(){
    _animationController = AnimationController(
      vsync: this,
      duration: Duration(seconds: 2)
    );
    _animationController.addListener((){
      print('Animation Controller Listener');
    });
    super.initState();
  }

答案 1 :(得分:0)

现在遇到相同的问题,但置顶器运行正常。您只需要启动它即可。

股票行情类

每个动画帧调用一次回调。

创建后,股票代码最初被禁用。呼叫开始以启用股票行情。

https://api.flutter.dev/flutter/scheduler/Ticker-class.html

所以基本上:

TickerProvider provider; // get a TickerProvider from somewhere.
Ticker ticker = provider.createTicker((elapsed) => print('tick ($elapsed)'));
ticker.start();

这将导致类似以下内容:

I/flutter (28439): tick (0:00:00.000000)
I/flutter (28439): tick (0:00:00.050374)
I/flutter (28439): tick (0:00:00.067166)
I/flutter (28439): tick (0:00:00.218288)
I/flutter (28439): tick (0:00:00.235081)

从开始算起的时间基本上是