gpt4 book ai didi

animation - Flutter:如何从父级控制动画

转载 作者:行者123 更新时间:2023-12-04 11:31:01 24 4
gpt4 key购买 nike

我需要从父小部件开始一个子小部件的动画。我怎样才能做到这一点?

我试过给 parent Controller ,但是你如何替换 vsync: this ?

这是基本代码(我还没有真正测试过这段代码,但我展示了我的意思):

import 'package:flutter/material.dart';

class ParentWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
ChildText(),
FlatButton(
child: Text('start the animation'),
onPressed: () {
// start the animation!!!????????
},
)
],
);
}
}

class ChildText extends StatefulWidget {
@override
_ChildTextState createState() => _ChildTextState();
}

class _ChildTextState extends State<ChildText> with TickerProviderStateMixin {
AnimationController _controller;
Animation _animation;

@override
void initState() {
super.initState();

// actual animation is much more complex, this is just a random demo
_controller =
AnimationController(vsync: this, duration: Duration(seconds: 2));

_animation = Tween(begin: -1.0, end: 100.0).animate(CurvedAnimation(
parent: _controller,
curve: Curves.fastOutSlowIn,
));
}

@override
Widget build(BuildContext context) {
return Transform.translate(
offset: Offset(0, _animation.value),
child: Text('Text with fancy animation'));
}
}

最佳答案

你可以试试这个:

class ParentWidget extends StatefulWidget {
@override
_ParentWidget createState() => _ParentWidget();
}

class _ParentWidget extends State<ParentWidget> with TickerProviderStateMixin {
AnimationController _controller;

@override
void initState() {
super.initState();
_controller =
AnimationController(vsync: this, duration: Duration(seconds: 2));
}

@override
void dispose() {
_controller.dispose();

super.dispose();
}

@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
ChildText(_controller),
FlatButton(
child: Text('start the animation'),
onPressed: () {
// start the animation!!!
_controller.forward();
},
)
],
);
}
}

class ChildText extends StatefulWidget {
ChildText(this._controller);

final AnimationController _controller;

@override
_ChildTextState createState() => _ChildTextState();
}

class _ChildTextState extends State<ChildText> with TickerProviderStateMixin {
Animation _animation;

@override
void initState() {
super.initState();

_animation = Tween(begin: -1.0, end: 100.0).animate(CurvedAnimation(
parent: widget._controller,
curve: Curves.fastOutSlowIn,
));
}

@override
Widget build(BuildContext context) {
return Transform.translate(
offset: Offset(0, _animation.value),
child: Text('Text with fancy animation'));
}
}

关于animation - Flutter:如何从父级控制动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58490402/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com