我正在使用自定义动画按钮。我想在用户每次点击动画时重复动画。因此,当用户单击它时,容器会放大。并返回到正常大小。当用户再次单击它时,它将再次执行该操作。现在,动画只是按比例缩放到定义的大小并停止。在那之后它什么也没做。
class CustomAnimation extends StatefulWidget {
@override
_CustomAnimationState createState() => _CustomAnimationState();
}
class _CustomAnimationState extends State<CustomAnimation> with SingleTickerProviderStateMixin {
AnimationController _controller;
@override
void initState() {
// TODO: implement initState
_controller = AnimationController(
vsync: this,
duration: Duration(seconds: 2),
);
_controller.addListener(() {
setState(() {
//do something
});
});
_controller.forward();
super.initState();
}
@override
void dispose() {
// TODO: implement dispose
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: AnimatedBuilder(
animation: _controller.view,
builder: (context,child){
return Transform.scale(scale: _controller.value *.9,
child: Container(
width: 200,
height: 200,
color: Colors.lightGreen[200],
child: Center(
child: Text('Animation test'),
),
),
);
},
),
)
);
}
}
答案 0 :(得分:2)
您可以在下面复制粘贴运行完整代码
您可以收听AnimationStatus.completed
并致电_controller.reverse()
并使用InkWell
调用_controller.forward();
animation = Tween<double>(begin: 1.0, end: 1.2).animate(_controller)
..addStatusListener((status) {
if (status == AnimationStatus.completed) {
_controller.reverse();
}
});
...
return Transform.scale(
scale: animation.value,
child: InkWell(
onTap: () {
_controller.forward();
},
工作演示
完整代码
import 'package:flutter/material.dart';
class CustomAnimation extends StatefulWidget {
@override
_CustomAnimationState createState() => _CustomAnimationState();
}
class _CustomAnimationState extends State<CustomAnimation>
with SingleTickerProviderStateMixin {
AnimationController _controller;
Animation<double> animation;
@override
void initState() {
_controller =
AnimationController(vsync: this, duration: Duration(seconds: 2));
_controller.addListener(() {
setState(() {
//do something
});
});
_controller.forward();
animation = Tween<double>(begin: 1.0, end: 1.2).animate(_controller)
..addStatusListener((status) {
if (status == AnimationStatus.completed) {
_controller.reverse();
}
});
super.initState();
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: AnimatedBuilder(
animation: animation,
builder: (context, child) {
return Transform.scale(
scale: animation.value,
child: InkWell(
onTap: () {
_controller.forward();
},
child: Container(
width: 200,
height: 200,
color: Colors.lightGreen[200],
child: Center(
child: Text('Animation test'),
),
),
),
);
},
),
));
}
}
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: CustomAnimation(),
);
}
}