Flutter - Add to Cart Animation
Last Updated :
24 Apr, 2025
In Building an E-commerce app, the "Add to Cart" animation is an essential part of it to attract users' attention. In this article, we will explore how to integrate the add_to_cart_animation package into the Flutter application, Here we are going to implement From installing the package to implementing various animation options. A sample video is given below to get an idea about what we are going to do in this article.
Step By Step Implementation
Step 1: Create a New Project in Android Studio
To set up Flutter Development on Android Studio please refer to Android Studio Setup for Flutter Development, and then create a new project in Android Studio please refer to Creating a Simple Application in Flutter.
Step 2: Adding the Dependencies
Here we have to add the the following dependencies to our pubspec.yaml file.
dependencies:
add_to_cart_animation: ^2.0.3
Or, Simply you can run the below command in your VS code Terminal.
flutter pub add add_to_cart_animation
Step 3: Import the Package
First of all import material.dart package and the add_to_cart_animation package.
import 'package:add_to_cart_animation/add_to_cart_animation.dart';
import 'package:flutter/material.dart';
Step 4: Execute the main Method
Here the execution of our app starts.
Dart
void main() {
runApp(const MyApp());
}
Step 5: Create MyApp Class
In this class we are going to implement the MaterialApp , here we are also set the Theme of our App.
Dart
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Shopping Cart Animation',
theme: ThemeData(
primarySwatch: Colors.green,
),
home: const ShoppingHomePage(),
debugShowCheckedModeBanner: false,
);
}
}
Step 6: Create ShoppingHomePage Class
The ShoppingHomePage class is a StatefulWidget in Flutter that serves as the main screen for a shopping application.The core functionalities of this class include displaying a dynamic and animated shopping cart icon in the AppBar with a badge indicating the quantity of items in the cart. The integration of the AddToCartAnimation package enables smooth animations when items are added to the cart. The shopping page utilizes a ListView.builder to display a list of shopping items, each represented by a ShoppingListItem. Users can interact with these items by tapping on them.Additionally, the page has a clear cart button to reset the cart and quantity.Comments are added for better understandings.
AddToCartAnimation(
cartKey: cartKey,
height: 25,
width: 25,
opacity: 0.80,
dragAnimation: const DragToCartAnimationOptions(rotation: true),
createAddToCartAnimation: (runAddToCartAnimation) {
this.runAddToCartAnimation = runAddToCartAnimation;
},
child: Scaffold(
appBar: AppBar(
title: const Text('Shopping Cart Animation'),
centerTitle: false,
actions: [
// Clear cart button
IconButton(
icon: const Icon(Icons.cancel_presentation),
onPressed: clearCart,
),
const SizedBox(width: 15),
// Shopping cart icon
AddToCartIcon(
key: cartKey,
icon: const Icon(Icons.shopping_cart),
badgeOptions: const BadgeOptions(
active: true,
backgroundColor: Colors.red,
),
),
const SizedBox(width: 16),
],
),
body: ListView.builder(
itemCount: 10,
itemBuilder: (context, index) => Column(
children: [
// Shopping list item
ShoppingListItem(onClick: listClick, index: index),
SizedBox(
height: 16), // Adjust the height according to your preference
],
),
),
),
);
Dart
class ShoppingHomePage extends StatefulWidget {
const ShoppingHomePage({Key? key}) : super(key: key);
@override
_ShoppingHomePageState createState() => _ShoppingHomePageState();
}
class _ShoppingHomePageState extends State<ShoppingHomePage> {
// Global key for the cart icon
final GlobalKey<CartIconKey> cartKey = GlobalKey<CartIconKey>();
late Function(GlobalKey) runAddToCartAnimation;
var _cartQuantityItems = 0;
@override
Widget build(BuildContext context) {
// Wrap the entire page with AddToCartAnimation
return AddToCartAnimation(
cartKey: cartKey,
height: 25,
width: 25,
opacity: 0.80,
dragAnimation: const DragToCartAnimationOptions(rotation: true),
createAddToCartAnimation: (runAddToCartAnimation) {
this.runAddToCartAnimation = runAddToCartAnimation;
},
child: Scaffold(
appBar: AppBar(
title: const Text('Shopping Cart Animation'),
centerTitle: false,
actions: [
// Clear cart button
IconButton(
icon: const Icon(Icons.cancel_presentation),
onPressed: clearCart,
),
const SizedBox(width: 15),
// Shopping cart icon
AddToCartIcon(
key: cartKey,
icon: const Icon(Icons.shopping_cart),
badgeOptions: const BadgeOptions(
active: true,
backgroundColor: Colors.red,
),
),
const SizedBox(width: 16),
],
),
body: ListView.builder(
itemCount: 10,
itemBuilder: (context, index) => Column(
children: [
// Shopping list item
ShoppingListItem(onClick: listClick, index: index),
SizedBox(
height: 16), // Adjust the height according to your preference
],
),
),
),
);
}
// Clear the cart and reset quantity
void clearCart() {
_cartQuantityItems = 0;
cartKey.currentState!.runClearCartAnimation();
}
// Handle item click, run animations
void listClick(GlobalKey widgetKey) async {
await runAddToCartAnimation(widgetKey);
await cartKey.currentState!
.runCartAnimation((++_cartQuantityItems).toString());
}
}
Step 7: Create ShoppingListItem Class
The ShoppingListItem class in Flutter represents an particular item in a shopping list. It displays a ListTile containing an image and a title. When tapped on the list items, the onClick function is triggered, then start the animation to add the items to the cart.Comments are added for better understandings.
Dart
class ShoppingListItem extends StatelessWidget {
final GlobalKey widgetKey = GlobalKey();
final int index;
final void Function(GlobalKey) onClick;
ShoppingListItem({required this.onClick, required this.index});
@override
Widget build(BuildContext context) {
// List of different image URLs for shopping items
List<String> shoppingImageUrls = [
"https://media.geeksforgeeks.org/wp-content/uploads/20231219221803/g4g-(1).jpg",
"https://media.geeksforgeeks.org/wp-content/uploads/20231221084839/images-(2).png",
"https://media.geeksforgeeks.org/wp-content/uploads/20231221084840/download-(3).png",
"https://media.geeksforgeeks.org/wp-content/uploads/20231221085010/images-(3).png",
];
// Select the image URL based on the index
String shoppingImageUrl =
shoppingImageUrls[index % shoppingImageUrls.length];
return ListTile(
onTap: () => onClick(widgetKey),
leading: Container(
key: widgetKey,
width: 55,
height: 55,
color: Colors.transparent,
child: Image.network(
shoppingImageUrl,
width: 55,
height: 55,
),
),
title: Text("Shopping Item $index"),
);
}
}
Here is the full Code of main.dart file
Dart
import 'package:add_to_cart_animation/add_to_cart_animation.dart';
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Shopping Cart Animation',
theme: ThemeData(
primarySwatch: Colors.green,
),
home: const ShoppingHomePage(),
debugShowCheckedModeBanner: false,
);
}
}
class ShoppingHomePage extends StatefulWidget {
const ShoppingHomePage({Key? key}) : super(key: key);
@override
_ShoppingHomePageState createState() => _ShoppingHomePageState();
}
class _ShoppingHomePageState extends State<ShoppingHomePage> {
// Global key for the cart icon
final GlobalKey<CartIconKey> cartKey = GlobalKey<CartIconKey>();
late Function(GlobalKey) runAddToCartAnimation;
var _cartQuantityItems = 0;
@override
Widget build(BuildContext context) {
// Wrap the entire page with AddToCartAnimation
return AddToCartAnimation(
cartKey: cartKey,
height: 25,
width: 25,
opacity: 0.80,
dragAnimation: const DragToCartAnimationOptions(rotation: true),
createAddToCartAnimation: (runAddToCartAnimation) {
this.runAddToCartAnimation = runAddToCartAnimation;
},
child: Scaffold(
appBar: AppBar(
title: const Text('Shopping Cart Animation'),
centerTitle: false,
actions: [
// Clear cart button
IconButton(
icon: const Icon(Icons.cancel_presentation),
onPressed: clearCart,
),
const SizedBox(width: 15),
// Shopping cart icon
AddToCartIcon(
key: cartKey,
icon: const Icon(Icons.shopping_cart),
badgeOptions: const BadgeOptions(
active: true,
backgroundColor: Colors.red,
),
),
const SizedBox(width: 16),
],
),
body: ListView.builder(
itemCount: 10,
itemBuilder: (context, index) => Column(
children: [
// Shopping list item
ShoppingListItem(onClick: listClick, index: index),
SizedBox(
height: 16), // Adjust the height according to your preference
],
),
),
),
);
}
// Clear the cart and reset quantity
void clearCart() {
_cartQuantityItems = 0;
cartKey.currentState!.runClearCartAnimation();
}
// Handle item click, run animations
void listClick(GlobalKey widgetKey) async {
await runAddToCartAnimation(widgetKey);
await cartKey.currentState!
.runCartAnimation((++_cartQuantityItems).toString());
}
}
class ShoppingListItem extends StatelessWidget {
final GlobalKey widgetKey = GlobalKey();
final int index;
final void Function(GlobalKey) onClick;
ShoppingListItem({required this.onClick, required this.index});
@override
Widget build(BuildContext context) {
// List of different image URLs for shopping items
List<String> shoppingImageUrls = [
"https://media.geeksforgeeks.org/wp-content/uploads/20231219221803/g4g-(1).jpg",
"https://media.geeksforgeeks.org/wp-content/uploads/20231221084839/images-(2).png",
"https://media.geeksforgeeks.org/wp-content/uploads/20231221084840/download-(3).png",
"https://media.geeksforgeeks.org/wp-content/uploads/20231221085010/images-(3).png",
];
// Select the image URL based on the index
String shoppingImageUrl =
shoppingImageUrls[index % shoppingImageUrls.length];
return ListTile(
onTap: () => onClick(widgetKey),
leading: Container(
key: widgetKey,
width: 55,
height: 55,
color: Colors.transparent,
child: Image.network(
shoppingImageUrl,
width: 55,
height: 55,
),
),
title: Text("Shopping Item $index"),
);
}
}
Output:
Similar Reads
Flutter - Card Flip Animation
Flutter is an open-source UI toolkit by Google. It is the favorite framework of many developers to build cross-platform apps because of its easy-to-learn curve. In this article, we are going to code a card flip animation in Flutter. Card flip animation is used in many places where you have to show a
2 min read
Flutter - Lottie Animation
Visualization is an integral part of any application. Animations can highly glorify the UI of an app, but animations can be hectic to implement for an application. This is where the Lottie animation comes in. Lottie is a JSON-based animation file. It can be used both as a network asset and a static
3 min read
Flutter - Circular reveal Animation
The Circular Reveal Animation in Flutter is inspired by ViewAnimationUtils.createCircularReveal(...). It does exactly what the name suggests, meaning it is used to reveal content generally an image circularly where the circle grows bigger and makes the image visible. In this article, we will impleme
4 min read
Flutter - Wave Animation
In this article, we are going to make a Flutter application that demonstrates the creation of a dynamic wave animation. This animation simulates the motion of water waves, creating an engaging visual effect that can be used in various Flutter applications to add styling effects. A sample video is gi
5 min read
Flutter - Spin Bottle Animation
In Flutter, Spin Bottle Animation is a fun and attractive animation, here we can achieve this by using the Flutter RotationTransition and AnimatedBuilder widget, In this animation, a bottle is rotated when we press a button. In this article, we are going to implement the Spin Bottle Animation using
5 min read
Flutter - Hinge Animation
Animations are a big part of the Flutter application. It makes an app sweet to the eyes and equally user-friendly. In this article, we will discuss in detail the Hinge animations. In Flutter there are two ways to work with animations namely:A pub packageAnimated Builder WidgetIn this article, we wil
4 min read
Flutter - AnimatedIcon Widget
Animation has become a vital part of UI design, whether it be a transition from one window to another or the closing of the window, the animation plays an important role in the smooth representation of the process. Just like that when we click on the icon, it shows animation, or another icon is show
3 min read
Flutter - Working with Animations
Whenever building an app animation plays a vital role in designing the experience of the user. People tend to like an app that has a smooth flow and a slick design. The Flutter Package provides a variety of methods to create and use animation in our app. We will be discussing the inbuilt Flutter wid
9 min read
Flutter - AnimatedContainer Widget
In Flutter a container is a simple widget with well-defined properties like height, width, and color, etc. The AnimatedContainer widget is a simple container widget with animations. These types of widgets can be animated by altering the values of their properties which are the same as the Container
3 min read
Flutter - Movie Tween Animation
Basically in Movie Tween Animation, we define different scenes, each with its own set of tweens and then Animate them. In Flutter we can achieve this type of animation easily by using the simple_animations package. In this article, we are going to implement the movie tween animation with the help of
6 min read