在重建时使用相同的Animationcontroller

时间:2020-04-06 23:17:32

标签: flutter flutter-animation flutter-test

我正在使用Tragtargets,如果东西在它们之上,它们会自我扩展。扩展动画总是从0开始,而收缩动画总是从1开始。如何使用相同的Animationcontroller来扩展收缩?因此,如果Target自身进行重建并想要缩小,则它将从控制器在扩展过程中拥有的最后一个值开始。例如,下面的代码应从重建之前的位置开始。有什么办法可以实现这样的目标?

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

class MyApp extends StatefulWidget {
  AnimationController controller;

  @override
  MyAppState createState() => new MyAppState();
}

class MyAppState extends State<MyApp> {

  @override
  Widget build(BuildContext context) {
    final title = 'Animated Container on Build';

    return new MaterialApp(
      title: title,
      home: Scaffold(
          appBar: AppBar(
            title: Text(title),
          ),
          body: Column(
            children: <Widget>[
              Row(
                children: <Widget>[
                  AniContainer(UniqueKey(),Duration(seconds: 2),widget.controller),
                ],
              ),
              RaisedButton(
                child: Text('press me'),
                  onPressed: ()=> setState(() {

                  }))
            ],
          )
      ),
    );
  }
}

class AniContainer extends StatefulWidget {
  Duration duration;
  AnimationController controller;
  AniContainer(Key key,this.duration,this.controller):super(key: key);
  @override
  _AniContainerState createState() => _AniContainerState();
}

class _AniContainerState extends State<AniContainer> with TickerProviderStateMixin{

  AnimationController _animationController;

  double getStart() {
    if (widget.controller==null) {
      return 1;
    }
    else {
      print(widget.controller.value);
      return widget.controller.value;
    }
  }

  @override
  void initState() {
    super.initState();
    widget.controller= AnimationController(vsync: this, duration:widget.duration,value: getStart())..reverse();
    _animationController= widget.controller;
  }

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

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: <Widget>[
        SizeTransition(
          axis: Axis.vertical,
          sizeFactor: _animationController,
          child: Container(
            height: 100,
            width: 100,
            color: Colors.red,
          ),
        ),
        Container(
          width: 100,
          height: 100,
          color: Colors.grey,
        )
      ],
    );
  }
}

0 个答案:

没有答案