Bounce Animation for Button in Flutter
This article explains you how to create bounce animation when users tap on button in flutter application. You can also check out flutter animations related articles.
In this flutter example, we are creating bouncing button animation without using any third party library or package. To make bounce button, first we need to initialize animation controller in initState method and implement SingleTicketProviderStateMixin widget class. We can dispose animation controller in dispose() method of stateful widget.
We can also set duration of bounce animation using duration property of AnimationController widget. We can also detect when button is tapped down and released using onTapDown and onTapUp callbacks of GestureDetector widget respectively.
We also need to scale button widget for animation. To create scale effect on button widget, we are using scale property of Transform.scale class of flutter transform widget. We can add our button as child widget in Transform.Scale class using child property.
Initialize Animation Controller
@override
_MyBounceAnimationScreenState createState() => _MyBounceAnimationScreenState();
}
class _MyBounceAnimationScreenState extends State<MyBounceAnimationScreen> with SingleTickerProviderStateMixin {
AnimationController animationController;
double scale;
@override
void initState() {
animationController = AnimationController(
vsync: this,
duration: Duration(
milliseconds: 300,
),
lowerBound: 0.0,
upperBound: 0.1,
)..addListener(() {
setState(() {});
});
super.initState();
}
@override
void dispose() {
super.dispose();
animationController.dispose();
}
}
Bounce Animation Button Widget
return Container(
width: 300,
height: 80,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(80),
boxShadow: [
BoxShadow(
color: Color(0x80000000),
blurRadius: 10,
offset: Offset(0,5),
),
],
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [
Colors.orangeAccent,
Colors.pinkAccent,
],
)),
child: Center(
child: Text(
‘Bounce Animation’,
style: TextStyle(
color: Colors.white,
fontSize: 28,
fontWeight: FontWeight.bold),
),
),
);
}
Flutter Bouncing Button UI
@override
Widget build(BuildContext context) {
scale = 1 – animationController.value;
return Scaffold(
appBar: AppBar(
title: Text(“Flutter Bounce Button Animation Sample”),
),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Center(
child: GestureDetector(
onTapUp: (TapUpDetails tapUPDetails){
animationController.reverse();
},
onTapDown: (TapDownDetails tapDownDetails){
animationController.forward();
},
child: Transform.scale(
scale: scale,
child: bounceButtonAnimationWidget(),
),
),
),
],
),
);
}
