Flutter动画插值

pit*_*zzo 5 animation flutter flutter-animation

我正在尝试基于一个动画来旋转一个小部件(这不是问题的一部分,因为它通过构造函数参数处理旋转本身),该动画在前一个旋转位置和通过插件函数获得的新旋转位置之间进行插值。该函数 ( ) 的值FlutterCompass.events.listen定期异步更新,并且每次都会重建 Tween 对象以表示 widget 位置的更新。这是我的代码:

import 'package:flutter/material.dart';
import 'package:flutter/animation.dart';
import 'package:flutter_compass/flutter_compass.dart';
import 'package:compass_test/compass.dart';

void main() => runApp(new MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => new _MyAppState();
}

class _MyAppState extends State<MyApp> with SingleTickerProviderStateMixin{
  double _direction;
  double _angle = 0.0;
  Animation<double> _animation;
  AnimationController _animationController;
  Tween<double> _tween;

  @override
  void initState() {
    super.initState();
      _animationController =
          AnimationController(duration: Duration(milliseconds: 400), vsync: this);
      _tween = Tween<double>(begin: 0.0, end: 0.0);
      _animation = _tween.animate(_animationController)
          ..addListener(() {
              setState(() {
                _angle =_animationController.value;
              });
          });
    _direction = 0;

    FlutterCompass.events.listen((double direction) {
      print(_animationController.status);
      if(_direction !=direction){
        _tween = Tween<double>(
          begin: _direction,
          end: direction);
        _animationController.reset();
        _tween.animate(_animationController);
        _animationController.forward();
      }
      _direction = direction;
    });
  }

  @override
  void dispose(){
    _animationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Column(
          children: <Widget>[
            Center(
              child: Container(
                margin: EdgeInsets.only(top: 100),
                child: Compass(height: 300, width: 300, angleToNorth: _angle)
              )
            )
          ],
        )
      ),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

然而,正如我在一些调试中看到的那样,返回的值_animationController.value仅在 0.0 到 1.0 之间变化,这不是我认为应该发生的情况:我期望它们从以前的值变化_direction到新direction值。我怎样才能做到这一点?

提前致谢

San*_*ant 0

这就是动画控制器应该如何工作的。通过一些额外的线条,您甚至可以添加一条曲线来表示从 0.0 到 1.0 的值变化。但值始终从 0.0 到 1.0。所以你可以做的就是像这样更新 _angles 值_angle = degree of angle * _animationController.value。假设你的角度是 50 度。因此,当您启动动画时,动画控制器的值将从 0.0 开始,乘以 50,得到 0。随着动画控制器的值从 0.0 移动到 1.0,_angle 的值也会发生变化,最终将 50 变为 1.0 * 50就是50!但正如您所提到的,您只想旋转您的小部件。因此,如果您想再次运行动画,您可以使用 double 类型的补间动画生成器来代替此方法并更新最终值;动画将从之前的值继续。