What is an Animated Icon in Flutter
In Flutter, an icon is a graphical representation of a specific action or object, such as a play button, a menu icon, or a shopping cart. By default, an icon is a static image that does not change or move. However, you can add animation to an icon to make it more engaging and interactive for users. An animated icon is an icon that moves, changes shape, or displays a visual effect in response to user input or a specific event.
Animating an icon in Flutter involves changing its appearance or behaviour over time using various animation techniques, such as changing its size, position, opacity, colour, or rotation. The animation can be triggered by user input, such as tapping on the icon, or by a specific event, such as a network request completing or a timer expiring.
There are many ways to animate an icon in Flutter, including using built-in widgets such as AnimatedIcon, TweenAnimationBuilder, and AnimatedOpacity, or creating custom animations using CustomPainter, Flare, or Lottie. Animating an icon can help draw attention to it, provide visual feedback to the user, or convey a sense of interactivity and dynamism to the app.
In summary, animating an icon in Flutter means adding movement and interactivity to a static graphical element in your app, making it more engaging and responsive to user input or events.
Visual effects with Icon Animation in Flutter
Flutter provides a range of visual effects that can be achieved with icon animation. Here are some examples:
- Spin Animation: This animation rotates the icon around its centre point. It can be used to draw attention to the icon or to indicate that it is being activated.
- Bounce Animation: This animation bounces the icon up and down. It can be used to give the icon a playful, fun feel or to indicate that it is clickable.
- Fade Animation: This animation gradually fades the icon in or out. It can be used to create a smooth transition between two screens or to indicate that an action is happening in the background.
- Scale Animation: This animation scales the icon up or down. It can be used to emphasize the icon’s importance or to indicate that it is being activated.
- Colour Change Animation: This animation changes the colour of the icon. It can be used to indicate that the icon is in a different state, such as selected or unselected.
- Pulse Animation: This animation makes the icon grow and shrink in size. It can be used to create a sense of urgency or to indicate that the icon is important.
- Shake Animation: This animation makes the icon shake back and forth. It can be used to draw attention to the icon or to indicate that something has gone wrong.
AnimatedIcon in Flutter
AnimatedIcon is a built-in widget in Flutter that allows you to animate icons with predefined animations. The widget animates an icon in response to an AnimationController, which you can use to control the animation’s duration, direction, and other properties.
To use AnimatedIcon, you need to provide an instance of AnimatedIconData that specifies the animation you want to use, and a reference to an AnimationController that controls the animation’s progress. You also need to specify the colour and size of the icon. Here’s an example of how to use AnimatedIcon to animate a menu icon:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> with SingleTickerProviderStateMixin {
late AnimationController _animationController;
@override
void initState() {
super.initState();
_animationController = AnimationController(
vsync: this,
duration: Duration(milliseconds: 500),
);
}
@override
void dispose() {
_animationController.dispose();
super.dispose();
}
void _onPressed() {
if (_animationController.isDismissed) {
_animationController.forward();
} else {
_animationController.reverse();
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('flutterassets.com'),
),
body: Container(
alignment: Alignment.topCenter,
padding: const EdgeInsets.all(8.0),
child: IconButton(
icon: AnimatedIcon(
icon: AnimatedIcons.menu_close,
progress: _animationController,
color: Colors.black,
size: 44,
),
onPressed: _onPressed,
)
),
);
}
}
In this example, the MenuButton widget creates an IconButton with an AnimatedIcon that animates a menu icon. The _onPressed
function toggles the animation between the menu and close states when the button is tapped. The vsync
parameter of the AnimationController is set to this
to use the widget as the animation’s tick source. Finally, the build function returns the IconButton with the AnimatedIcon inside it.
In summary, using AnimatedIcon to animate icons in Flutter is a straightforward process that involves creating an instance of AnimatedIconData, a reference to an AnimationController, and passing them to an AnimatedIcon widget. The widget automatically animates the icon based on the animation data and controller you provided.
“vsync: this” error in Flutter
Error: The argument type ‘_MyHomePageState’ can’t be assigned to the parameter type ‘TickerProvider’.
This error is typically caused by not adding the with TickerProviderStateMixin
mixin to your widget state class. When you create an AnimationController
instance, you need to specify a TickerProvider that will drive the animation.
To fix this error, you can either implement the TickerProvider
interface in your _MyHomePageState
class or use a widget that already implements it, such as the SingleTickerProviderStateMixin
.
Here’s an example of how to use SingleTickerProviderStateMixin
in a stateful widget:
class _MyHomePageState extends State<MyHomePage> with TickerProviderStateMixin {
// ...
}
Flutter Icon Size Animation with TweenAnimationBuilder
You can use the TweenAnimationBuilder
widget to animate the size of an Icon or IconButton in Flutter. The TweenAnimationBuilder
widget can animate a value between two endpoints using a Tween
, and update the state of the widget when the value changes.
Here is an example code that demonstrates how to use TweenAnimationBuilder
to animate the size of an IconButton
:
double _iconSizeStart = 24.0;
double _iconSizeEnd = 48.0;
bool _isIconBig = false;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('flutterassets.com'),
),
body: Container(
alignment: Alignment.topCenter,
padding: const EdgeInsets.all(8.0),
child: TweenAnimationBuilder<double>(
tween: Tween<double>(
begin: _iconSizeStart,
end: _isIconBig ? _iconSizeEnd : _iconSizeStart,
),
duration: Duration(milliseconds: 500),
builder: (BuildContext context, double size, Widget? child) {
return IconButton(
iconSize: size,
icon: Icon(Icons.favorite, color: Colors.red,),
onPressed: () {
setState(() {
_isIconBig = !_isIconBig;
});
},
);
},
)
),
);
}
In this example, the initial size of the Icon
is 24.0. We use the TweenAnimationBuilder
widget to animate the size of the IconButton
between the initial size of 24.0 and the target size of 48.0 when the user taps on the button. The animation takes 500 milliseconds to complete.
We use a boolean flag _isIconBig
to toggle the size of the IconButton
between small and big when the user taps on it. We also pass the current size of the IconButton
as a parameter to the builder
function of the TweenAnimationBuilder
, where we update the size of the IconButton
based on the current animation value.
When the user taps on the IconButton
, we call setState()
to rebuild the widget with the updated _isIconBig
flag, which triggers the animation to run and updates the state of the widget with the new size of the IconButton
.
Flutter Icon Scale Animation with ScaleTransition
hire is another code to scale an Icon onTap:
late AnimationController _controller;
bool _isScaled = false;
@override
void initState() {
super.initState();
_controller =
AnimationController(vsync: this, duration: Duration(milliseconds: 200));
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('flutterassets.com'),
),
body: Container(
alignment: Alignment.topCenter,
padding: const EdgeInsets.all(8.0),
child: GestureDetector(
onTap: () {
_isScaled = !_isScaled;
_isScaled
? _controller.forward()
: _controller.reverse();
},
child: ScaleTransition(
scale: Tween(begin: 1.0, end: 1.5).animate(_controller),
child: Icon(Icons.favorite, size: 50,),
),
),
),
);
}
In this code, we use the GestureDetector
widget to detect a tap on the icon. When the icon is tapped, we toggle the _isScaled
boolean variable and call either the forward
or reverse
method on the _controller
, depending on whether the icon should be scaled up or down.
The ScaleTransition
widget is used to scale the Icon
widget. We define an animation that scales the icon from 1.0 to 1.5 using a Tween
. The Tween
is animated by the _controller
, which we pass as an argument to Tween.animate
.
Flutter Icon Scale Animation with Transform.scale
bool _isFirstIcon = true;
late AnimationController _controller;
late Animation<double> _animation;
@override
void initState() {
super.initState();
_controller = AnimationController(
vsync: this,
duration: Duration(milliseconds: 500),
);
_animation = Tween<double>(begin: 1.0, end: 0.0).animate(_controller)
..addListener(() {
setState(() {});
});
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('flutterassets.com'),
),
body: Container(
alignment: Alignment.topCenter,
padding: const EdgeInsets.all(8.0),
child: GestureDetector(
onTap: () {
if (_isFirstIcon) {
_controller.forward();
} else {
_controller.reverse();
}
_isFirstIcon = !_isFirstIcon;
},
child: Stack(
alignment: Alignment.center,
children: [
Transform.scale(
scale: _animation.value,
child: Icon(Icons.check, size: 48.0),
),
Transform.scale(
scale: 1 - _animation.value,
child: Icon(Icons.close, size: 48.0),
),
],
),
)
),
);
}
In this code, we use a Stack
widget to display two Icon
widgets, one for each state. When the user taps on the widget, we animate the scale of the first Icon
to 0, and the scale of the second Icon
to 1, effectively making it appear as if the first Icon
is scaling down while the second Icon
is scaling up. Tapping the widget again reverses the animation, making the first Icon
scale up while the second Icon
scales down.
Flutter Icon Background Colour Animation
You can use an AnimatedContainer widget to animate the colour of an Icon or IconButton in Flutter. The AnimatedContainer widget automatically animates any changes made to its properties, including colour.
Here’s an example code that demonstrates how to animate the colour of an IconButton using the AnimatedContainer widget:
bool _isPressed = false;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('flutterassets.com'),
),
body: Container(
alignment: Alignment.topCenter,
padding: const EdgeInsets.all(8.0),
child: AnimatedContainer(
duration: const Duration(milliseconds: 500),
decoration: BoxDecoration(
color: _isPressed ? Colors.green : Colors.red,
borderRadius: BorderRadius.circular(50),
),
child: IconButton(
onPressed: () {
setState(() {
_isPressed = !_isPressed;
});
},
icon: Icon(Icons.favorite),
color: Colors.white,
),
),
),
);
}
In this example, we use an AnimatedContainer widget to animate the background colour of the container that wraps the IconButton. The duration of the animation is set to 500 milliseconds using the duration
property of the AnimatedContainer. The decoration
property of the AnimatedContainer is set to a BoxDecoration that specifies the background colour and a border radius of 50. The color
property of the IconButton is set to white to contrast with the background colour of the container.
When the IconButton is pressed, the _isPressed
variable is toggled and the state of the widget is updated using setState
. This causes the AnimatedContainer to animate the change in background colour from red to green or vice versa.
Flutter Icon Colour Animation
To animate the colour of an Icon only in Flutter, we can use the TweenAnimationBuilder
widget. This widget creates an animation that takes a value from one range to another, and then we can use this value to set the colour of the Icon.
Here’s an example code that animates the colour of an Icon using TweenAnimationBuilder
:
bool _isRed = false;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('flutterassets.com'),
),
body: Container(
alignment: Alignment.topCenter,
padding: const EdgeInsets.all(8.0),
child: GestureDetector(
onTap: (){
setState(() {
_isRed = !_isRed;
});
},
child: TweenAnimationBuilder(
tween: ColorTween(
begin: Colors.blue,
end: _isRed ? Colors.red : Colors.blue,
),
duration: Duration(seconds: 1),
builder: (context, color, child) {
return Icon(
Icons.star,
color: color,
size: 50.0,
);
},
),
)
),
);
}
In this code, we first create a bool
variable _isRed
to keep track of whether the colour of the Icon is blue or not. We then use TweenAnimationBuilder and pass a ColorTween object to its tween parameter, which specifies the starting and ending colours of the animation.
We also set the duration
of the animation to 1 second. In the builder
function of the TweenAnimationBuilder
, we receive the current value of the animation (the current colour), which we then use to set the colour of the Icon.
Finally, we return an Icon widget with the specified size and the current colour. When _isRed is toggled, the colour of the Icon will animate from blue to red or green, depending on the value of _isRed
.
The animation is triggered with the GestureDetector and changes the state of the _isRed
value.
Flutter Animation between Icons with Transform
To create a transition between two icons we can use AnimatedSwitcher
widget. When the user taps the IconButton
, the widget swaps the current icon with a new one, animating the transition between the two.
bool _showAddIcon = true;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('flutterassets.com'),
),
body: Container(
alignment: Alignment.topCenter,
padding: const EdgeInsets.all(8.0),
child: Container(
width: 80,
height: 80,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: Colors.blue,
),
child: AnimatedSwitcher(
duration: Duration(milliseconds: 1000),
child: IconButton(
iconSize: 50,
key: ValueKey<bool>(_showAddIcon),
icon: Icon(
_showAddIcon ? Icons.home : Icons.share_outlined,
color: _showAddIcon ? Colors.red : Colors.white,
),
onPressed: () {
setState(() {
_showAddIcon = !_showAddIcon;
});
},
),
),
)
),
);
}
The above code creates a boolean variable _showAddIcon
that is used to determine which icon to show. The IconButton
widget initially displays the Icons.home
icon, but when the user taps on it, the _showAddIcon
variable is toggled and the AnimatedSwitcher
widget animates the transition to the Icons.share_outlined
icon. The AnimatedSwitcher
widget is wrapped around the IconButton
widget and takes a duration
parameter that sets the length of the animation.
In order for the AnimatedSwitcher
to correctly animate the transition, each icon needs to have a unique key. The IconButton
widget takes a key
property that sets a unique key for each icon. This ensures that the AnimatedSwitcher
can correctly animate the transition between the two icons.
In summary, the AnimatedSwitcher
widget is used in the attached code to animate the transition between two icons. When the user taps the IconButton
, the widget swaps the current icon with a new one and animates the transition between the two. The AnimatedSwitcher
takes a duration
parameter and the IconButton
widget takes a key
property to ensure that the transition is animated correctly.
Fade-Out and Fade-In Flutter Icon Animation
This is another example of how to create an animated icon in Flutter that fades out and fades in a new icon on tap, you can use the AnimatedSwitcher
widget with FadeTransition
. Here is an example code that demonstrates the concept:
bool _isFirstIconVisible = true;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('flutterassets.com'),
),
body: Container(
alignment: Alignment.topCenter,
padding: const EdgeInsets.all(16.0),
child: Column(
children: [
GestureDetector(
onTap: () {
setState(() {
_isFirstIconVisible = !_isFirstIconVisible;
});
},
child: AnimatedSwitcher(
duration: Duration(milliseconds: 300),
transitionBuilder: (child, animation) => FadeTransition(
opacity: animation,
child: child,
),
child: _isFirstIconVisible
? Icon(
Icons.favorite,
size: 100.0,
color: Colors.red,
key: ValueKey('first'),
)
: Icon(
Icons.star,
size: 100.0,
color: Colors.blue,
key: ValueKey('second'),
),
),
),
],
)
),
);
}
In this example, the AnimatedSwitcher
widget is used to animate between the two icons. The duration
property sets the duration of the animation, and the transitionBuilder
property specifies the type of transition used between the two icons.
The onTap
handler toggles the _isFirstIconVisible
boolean, which triggers the AnimatedSwitcher
to animate between the two icons. The key
property is used to differentiate between the two icons, so the AnimatedSwitcher
knows which one to fade out and which one to fade in.
Slide-In Icon Animation in Flutter
You can use a combination of an AnimatedSwitcher
and SlideTransition
to create an animated icon that slides out and disappears when clicked, while a new icon slides in to take its place. Here’s an example code that demonstrates the idea:
bool _showFirstIcon = true;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('flutterassets.com'),
),
body: Container(
alignment: Alignment.topCenter,
padding: const EdgeInsets.all(8.0),
child: GestureDetector(
onTap: () {
setState(() {
_showFirstIcon = !_showFirstIcon;
});
},
child: AnimatedSwitcher(
duration: Duration(milliseconds: 500),
transitionBuilder: (Widget child, Animation<double> animation) {
return SlideTransition(
position: Tween<Offset>(
begin: Offset(1, 0),
end: Offset.zero,
).animate(animation),
child: child,
);
},
child: _showFirstIcon
? Icon(
Icons.star,
size: 70,
color: Colors.red,
key: ValueKey<bool>(_showFirstIcon),
)
: Icon(
Icons.favorite,
size: 70,
color: Colors.blue,
key: ValueKey<bool>(_showFirstIcon),
),
),
),
),
);
}
In this code, we use a boolean _showFirstIcon
to keep track of which icon to show. We wrap the Icon
widgets with an AnimatedSwitcher
, which provides an animation when switching between the icons. We also set the duration
property of the AnimatedSwitcher
to 500 milliseconds to make the animation slower and more visible.
We also set the transitionBuilder
property of the AnimatedSwitcher
to define how the transition between the icons should be animated. Here, we use a SlideTransition
widget to make the old icon slide out to the right and disappear while the new icon slides in from the left to take its place. We use an Offset
animation with a Tween
that starts at (1, 0)
(i.e. the right side of the screen) and ends at Offset.zero
(i.e. the centre of the screen) to control the position of the transition.
Finally, we wrap the AnimatedSwitcher
with a GestureDetector
and set its onTap
property to toggle the value of _showFirstIcon
and trigger the transition between the two icons.
Flutter Icon Rotate Animation onPressed
Here is an example code that rotates an icon when clicked:
late AnimationController _controller;
@override
void initState() {
super.initState();
_controller =
AnimationController(vsync: this, duration: Duration(seconds: 1));
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('flutterassets.com'),
),
body: Container(
alignment: Alignment.topCenter,
padding: const EdgeInsets.all(8.0),
child: GestureDetector(
onTap: () {
_controller.reset();
_controller.forward();
},
child: RotationTransition(
turns: Tween(begin: 0.0, end: 2.0).animate(_controller),
child: Icon(Icons.refresh, size: 50,),
),
),
),
);
}
The animation is achieved by using a RotationTransition
widget and a GestureDetector
. When the user taps on the icon, the GestureDetector
triggers a callback function that starts the rotation animation.
The rotation animation is controlled by an AnimationController
. The AnimationController
allows us to define a duration and an animation curve for the animation. In this case, we are using a CurvedAnimation
with a decelerate
curve to create a smooth and natural-looking rotation.
The RotationTransition
widget is then used to apply the rotation animation to the icon. We pass the AnimationController
to the RotationTransition
widget and define the rotation angle using the angle
parameter. We calculate the angle based on the current value of the AnimationController
.
When the user taps on the icon, the GestureDetector
triggers the callback function, which starts the animation by calling the forward
method on the AnimationController
. This causes the icon to rotate 360 degrees over the duration of the animation.
Overall, the code creates a simple but effective animation that adds some visual interest to the icon when the user taps on it.
Bouncing Icon Animation in Flutter
To make an icon animation in Flutter where the icon constantly moves up and down, like a bouncing effect, you can use a combination of Tween
animation and AnimatedBuilder
.
Here is an example code that you can modify to achieve this effect:
class _MyHomePageState extends State<MyHomePage> with SingleTickerProviderStateMixin {
late AnimationController _controller;
late Animation<double> _animation;
@override
void initState() {
super.initState();
_controller = AnimationController(
duration: Duration(milliseconds: 800),
vsync: this,
)..repeat(reverse: true);
_animation = Tween<double>(begin: 0.0, end: 1.0).animate(
CurvedAnimation(
parent: _controller,
curve: Curves.easeInCirc,
),
);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('flutterassets.com'),
),
body: Container(
alignment: Alignment.topCenter,
padding: const EdgeInsets.all(16.0),
child: Column(
children: [
AnimatedBuilder(
animation: _animation,
builder: (context, child) {
return Transform.translate(
offset: Offset(
0.0,
-20.0 * _animation.value,
),
child: child,
);
},
child: Icon(
Icons.cloud_circle_rounded,
size: 70.0,
color: Colors.blue,
),
)
],
)
),
);
}
}
In the initState
method, we create an AnimationController
and an Animation
object. We set the duration of the animation to 800 milliseconds and make it repeat in reverse. We also set the curve of the animation to Curves.easeInOutBack
, which creates a bouncing effect.
In the build
method, we use an AnimatedBuilder
to rebuild the widget tree on each frame of the animation. We then use a Transform.translate
widget to move the Icon
up and down based on the value of the animation.
Finally, we return the Icon
widget with a size of 70.0 to display the bouncing effect. You can modify the Icon
to any other icon you want to use in your app.
Flutter Icon Pulse Animation with FadeTransition (opacity animation)
To create a pulse animation of an icon in Flutter, you can use the AnimatedOpacity
widget in combination with a TweenSequence
to define the animation sequence. The AnimatedOpacity
widget allows us to change the opacity of a widget over time, which can give the impression of a pulse effect.
Here’s an example of how you can create a pulse animation of an icon in Flutter:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> with SingleTickerProviderStateMixin {
late AnimationController _animationController;
@override
void initState() {
super.initState();
_animationController = AnimationController(
vsync: this,
duration: const Duration(seconds: 1),
)..repeat();
}
@override
void dispose() {
_animationController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('flutterassets.com'),
),
body: Container(
alignment: Alignment.topCenter,
padding: const EdgeInsets.all(8.0),
child: FadeTransition(
opacity: TweenSequence([
TweenSequenceItem<double>(
tween: Tween<double>(begin: 1, end: 0.3)
.chain(CurveTween(curve: Curves.easeInOut)),
weight: 1,
),
TweenSequenceItem<double>(
tween: Tween<double>(begin: 0.3, end: 1)
.chain(CurveTween(curve: Curves.easeInOut)),
weight: 1,
),
]).animate(_animationController),
child: IconButton(
iconSize: 60,
color: Colors.red,
icon: Icon(Icons.favorite),
onPressed: () {},
),
)
),
);
}
}
In the above code, we define a PulseIcon
widget which contains an AnimatedOpacity
widget and an IconButton
. The AnimatedOpacity
widget takes care of the pulse animation, while the IconButton
defines the icon that will be displayed.
We also define an AnimationController
and use the repeat()
method to make the pulse animation loop indefinitely. We then define a TweenSequence
that defines the opacity values for the animation. The TweenSequence
consists of two TweenSequenceItem
objects, each of which defines a Tween
and a weight. The weights determine the proportion of time spent on each TweenSequenceItem
. In this example, we spend an equal amount of time on each TweenSequenceItem
.
Finally, we apply the TweenSequence
animation to the opacity
property of the FadeTransition
, and pass in the AnimationController
to control the animation.
Flutter Icon Pulse Animation (size animation)
To create a pulse animation of an icon in Flutter, you can use an AnimatedContainer
widget with a Tween
animation that updates the size of the icon. Here is an example of how you can implement this:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> with SingleTickerProviderStateMixin {
late AnimationController _animationController;
late Animation<double> _animation;
double size = 50;
@override
void initState() {
super.initState();
_animationController =
AnimationController(vsync: this, duration: Duration(milliseconds: 800))
..repeat(reverse: true);
_animation =
Tween<double>(begin: 1.0, end: 1.3).animate(_animationController);
}
@override
void dispose() {
_animationController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('flutterassets.com'),
),
body: Container(
alignment: Alignment.topCenter,
padding: const EdgeInsets.all(8.0),
child: AnimatedBuilder(
animation: _animation,
builder: (BuildContext context, Widget? child) {
return Container(
child: Icon(
Icons.favorite,
color: Colors.red,
size: size * _animation.value,
),
);
},
)
),
);
}
}
In this example the initState
method sets up an AnimationController
with a duration of 800 milliseconds that repeats infinitely and reverses direction at the end of each cycle. The Tween
animation is used to interpolate the icon size from 1.0 to 1.3.
The build
method creates an AnimatedBuilder
widget that listens to the animation updates and rebuilds the Icon
widget with the new size value. The size value is calculated by multiplying the original size with the current value of the animation. This creates the pulsing effect of the icon.
Pulse Icon Animation in Flutter (scale animation)
To create a pulse animation that animates the scale of an icon in Flutter, we can use the Tween
class to define a range of values for the scale, and then use an AnimationController
and CurvedAnimation
to create a smooth animation.
Here is an example code:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> with SingleTickerProviderStateMixin {
late AnimationController _animationController;
late Animation<double> _scaleAnimation;
@override
void initState() {
super.initState();
// Define the animation controller
_animationController = AnimationController(
vsync: this,
duration: Duration(milliseconds: 800),
)..repeat(reverse: true);
// Define the scale animation
_scaleAnimation = Tween<double>(begin: 1, end: 1.5).animate(
CurvedAnimation(parent: _animationController, curve: Curves.easeInOut));
}
@override
void dispose() {
_animationController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('flutterassets.com'),
),
body: Container(
alignment: Alignment.topCenter,
padding: const EdgeInsets.all(8.0),
child: ScaleTransition(
scale: _scaleAnimation,
child: Icon(
Icons.favorite,
color: Colors.red,
size: 60,
),
)
),
);
}
}
In the initState()
method, we define the animation controller with the given duration and set it to repeat in reverse mode. Then we define the scale animation using a Tween
that animates the scale of the icon from 1 to 1.5. We use a CurvedAnimation
to create a smooth animation curve.
In the build()
method, we use a ScaleTransition
widget to apply the scale animation to the Icon
widget. The iconData
, color
, and size
parameters are passed in from the widget’s constructor.
With this implementation, the icon will smoothly pulse between its original size and 1.5 times its original size, creating a pulsing effect.
Shake Icon Animation in Flutter (rotation animation)
To create a shake animation of an icon in Flutter, we can use the Tween
and AnimationController
classes. The Tween
class helps us to define the range of values we want to animate between, while the AnimationController
class helps us to control the duration and speed of the animation.
First, we need to create an AnimationController
object with a duration and a vsync
parameter. The vsync
parameter helps to synchronize the animation with the device’s refresh rate. Then, we need to create a Tween
object to define the range of values we want to animate. In this case, we want to animate the rotation of the icon. We can use the RotationTransition
widget to animate the rotation of the icon.
Here is an example code to create a shake animation of an icon in Flutter:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> with SingleTickerProviderStateMixin {
late AnimationController _controller;
late Animation<double> _animation;
@override
void initState() {
super.initState();
_controller = AnimationController(
duration: Duration(milliseconds: 500),
vsync: this,
)..repeat(reverse: true);
_animation = Tween<double>(begin: -0.05, end: 0.05).animate(
CurvedAnimation(
parent: _controller,
curve: Curves.easeInOut,
),
);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('flutterassets.com'),
),
body: Container(
alignment: Alignment.topCenter,
padding: const EdgeInsets.all(8.0),
child: RotationTransition(
turns: _animation,
child: IconButton(
icon: Icon(Icons.favorite, size: 60,color: Colors.red,),
onPressed: () {},
),
)
),
);
}
}
In the above code, we create a ShakeIcon
widget that returns a RotationTransition
widget with the IconButton
widget as its child. We create an AnimationController
object with a duration of 500 milliseconds and use the repeat
method to repeat the animation in reverse direction. We also create a Tween
object to define the range of values we want to animate, which is between -0.05 and 0.05. We use the CurvedAnimation
class to define the easing curve for the animation. Finally, we use the RotationTransition
widget to animate the rotation of the icon using the _animation
variable.
Overall, the ShakeIcon
widget animates the rotation of the icon in a shake motion, by repeatedly rotating it back and forth by a small angle.
Flutter Icon Shake Animation (translate animation)
To create a Shake animation in Flutter, we can use the Tween
class to create a sequence of values that we can animate. In this case, we will create a sequence of Offset
values that will represent the position of the icon as it shakes back and forth.
Here’s an example code snippet that shows how to create a Shake animation in Flutter:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> with SingleTickerProviderStateMixin {
late AnimationController _controller;
late Animation<Offset> _animation;
@override
void initState() {
super.initState();
_controller = AnimationController(
vsync: this,
duration: Duration(milliseconds: 200),
);
_animation = Tween<Offset>(
begin: Offset(-5, 0.0),
end: Offset(5, 0.0),
).animate(CurvedAnimation(
parent: _controller,
curve: Curves.linear,
));
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
void _startAnimation() {
_controller.repeat(reverse: true);
}
void _stopAnimation() {
_controller.stop();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('flutterassets.com'),
),
body: Container(
alignment: Alignment.topCenter,
padding: const EdgeInsets.all(8.0),
child: GestureDetector(
onTap: _startAnimation,
onLongPress: _stopAnimation,
onTapUp: (_) => _stopAnimation(),
child: AnimatedBuilder(
animation: _animation,
builder: (context, child) {
return Transform.translate(
offset: _animation.value,
child: Icon(Icons.favorite, size: 60,),
);
},
),
)
),
);
}
}
In this code, we create a new ShakeIcon
widget that takes an IconData
as a parameter. The widget extends StatefulWidget
and uses the SingleTickerProviderStateMixin
mixin.
In the initState
method, we create a new AnimationController
and a Tween<Offset>
that defines the range of values for the animation. We set the begin value to -5
and the end value to 0.5
, which means the icon will shake horizontally by 5% of its width. We also define the duration of the animation and the curve that defines how the animation progresses over time.
In the build
method, we use a GestureDetector
to handle tap events on the icon. When the user taps on the icon, we start the animation by calling _controller.repeat(reverse: true)
. This will cause the animation to repeat back and forth between the begin and end values. When the user use the onLongPress
, we stop the animation by calling _controller.stop()
. We also use an AnimatedBuilder
to animate the position of the icon based on the current value of the _animation
object.
Finally, we use the Transform.translate
widget to apply the offset to the icon, which will cause it to shake horizontally. The Transform
widget is used to apply various transformations to widgets in Flutter, including scaling, rotating, and translating.