📅  最后修改于: 2023-12-03 15:12:07.922000             🧑  作者: Mango
在前端开发中,有时需要实现容器高度抖动的效果。此时,可使用 Dart 编程语言轻松实现此功能。
import 'package:flutter/material.dart';
class ShakingContainer extends StatefulWidget {
final Widget child;
final double shakeHeight;
const ShakingContainer({
Key key,
@required this.child,
this.shakeHeight = 50.0,
}) : super(key: key);
@override
_ShakingContainerState createState() => _ShakingContainerState();
}
class _ShakingContainerState extends State<ShakingContainer>
with SingleTickerProviderStateMixin {
AnimationController _controller;
Animation<double> _animation;
@override
void initState() {
super.initState();
_controller =
AnimationController(vsync: this, duration: Duration(seconds: 1));
_animation = Tween<double>(begin: 0, end: widget.shakeHeight).animate(
CurvedAnimation(parent: _controller, curve: Curves.easeInOut),
);
_controller.addStatusListener((status) {
if (status == AnimationStatus.completed) {
_controller.reverse();
} else if (status == AnimationStatus.dismissed) {
_controller.forward();
}
});
_controller.forward();
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return AnimatedBuilder(
animation: _animation,
builder: (context, child) {
return Container(
height: widget.shakeHeight + _animation.value,
child: widget.child,
);
},
);
}
}
ShakingContainer(
shakeHeight: MediaQuery.of(context).size.height * 0.25,
child: Container(
height: 100.0,
color: Colors.blue,
),
)
通过以上两步,即可轻松实现容器高度抖动 25% 的屏幕的效果。其中,通过 AnimationController 和 Tween 实现了容器高度从 0 到 shakeHeight 的动画效果,可自行修改 shakeHeight 的值实现不同的高度抖动。同时,通过 AnimatedBuilder 实现动画效果的构建。