Flutter动画插值

5

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

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)
              )
            )
          ],
        )
      ),
    );
  }
}

然而,通过一些调试,我发现从 _animationController.value 返回的值只在0.0到1.0之间变化,这不是我以为会发生的情况:我期望它们应该从 _direction 的先前值变化到新的 direction 值。我该如何实现?
提前感谢。
1个回答

0
这就是动画控制器的工作原理。通过添加一些额外的代码,您甚至可以将值从0.0到1.0的变化添加到曲线中。但是,这些值始终会从0.0到1.0。因此,您可以像这样更新_angles的值:_angle = 角度的度数 * _animationController.value。假设您的角度为50度。当您启动动画时,动画控制器的值将从0.0开始,这将乘以50,得到0。随着动画控制器的值从0.0到1.0的变化,_angle的值也会发生变化,并最终给您50,因为1.0 * 50等于50!但是,正如您所提到的,您只想旋转小部件。因此,您可以使用类型为double的补间动画构建器,并在需要再次运行动画时更新结束值;动画将从先前的值继续进行。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接