Open In App

Flutter – Add to Cart Animation

Last Updated : 09 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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 = [
    ];
  
    // 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 = [
    ];
  
    // 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:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads