flutter_card_swiper

repository·main·Indexed 42 days ago

https://github.com/ricardodalarme/flutter_card_swiper

A Flutter package providing a highly customizable, Tinder-like card swiping interface. It supports multi-directional swiping (left, right, up, down), undo functionality, and programmatic control via the CardSwiperController. Key features include customizable physics, direction detection using CardSwiperDirection, and flexible swipe restrictions via AllowedSwipeDirection.

Tokens
5.5K
Snippets
13
Records
18
Agent score
52%

What's inside flutter_card_swiper

  1. Key features of flutter_card_swiper

    main

    The flutter_card_swiper package provides a highly customizable Tinder-like swiping experience with the following capabilities:

    • Multi-directional swiping: Supports swiping left, right, up, and down.
    • Undo functionality: Allows users to unswipe cards as many times as needed.
    • Customizable physics: Adjust settings such as animation duration, swipe angle, and padding.
    • Programmatic control: Trigger swipes in any direction using a controller.
    • Callbacks: Hooks for when a user is swiping, when a swipe ends, or when the swiper is disabled.
    • Direction detection: Detect whether a card was swiped left, right, top, or bottom.
  2. Customize iOS launch screen assets

    main

    To change the launch screen image for the iOS version of your Flutter app, you can use one of two methods:

    1. Direct File Replacement: Replace the existing image files directly within the example/ios/Runner/Assets.xcassets/LaunchImage.imageset/ directory with your own assets.
    2. Xcode Interface:
      • Open the iOS project in Xcode by running open ios/Runner.xcworkspace from your terminal.
      • In the Xcode Project Navigator, navigate to Runner/Assets.xcassets.
      • Drag and drop your desired images into the asset catalog to replace the current ones.
    open ios/Runner.xcworkspace
  3. Basic usage of CardSwiper

    main

    To implement a card swiper, use the CardSwiper widget. You must provide the total number of cards via cardsCount and a cardBuilder function that returns the widget for a specific index. The cardBuilder provides the current context, the card index, and threshold percentages for X and Y axes.

    import 'package:flutter_card_swiper/flutter_card_swiper.dart';
    import 'package:flutter/material.dart';
    
    class Example extends StatelessWidget {
      List<Container> cards = [
        Container(
          alignment: Alignment.center,
          child: const Text('1'),
          color: Colors.blue,
        ),
        Container(
          alignment: Alignment.center,
          child: const Text('2'),
          color: Colors.red,
        ),
        Container(
          alignment: Alignment.center,
          child: const Text('3'),
          color: Colors.purple,
        )
      ];
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: Flexible(
            child: CardSwiper(
              cardsCount: cards.length,
              cardBuilder: (context, index, percentThresholdX, percentThresholdY) => cards[index],
            ),
          ),
        );
      }
    }
  4. Use CardSwiperController to control swipes programmatically

    main

    To trigger swipe actions, undo actions, or jump to specific cards from outside the CardSwiper widget, use the CardSwiperController.

    1. Create an instance of CardSwiperController.
    2. Pass this instance to the controller parameter of the CardSwiper widget.
    3. Call the desired methods on the controller instance.
    final CardSwiperController controller = CardSwiperController();
    
    // In your widget tree
    CardSwiper(
      controller: controller,
      cardBuilder: (index, indexFromEnd) => MyCard(index),
      cardsCount: 10,
    );
    
    // To trigger actions elsewhere (e.g., in an IconButton callback)
    void _onSwipeRight() {
      controller.swipe(CardSwiperDirection.right);
    }
    
    void _onUndo() {
      controller.undo();
    }
    
    void _goToFirstCard() {
      controller.moveTo(0);
    }
  5. Configure the CardSwiper constructor

    main

    The CardSwiper widget is configured using several parameters to control the behavior, appearance, and interaction of the card stack.

    Required Parameters:

    • cardBuilder: A function that returns the widget to be rendered as a card.
    • cardsCount: The total number of cards in the stack.

    Key Configuration Options:

    • controller: An instance of CardSwiperController to trigger actions programmatically.
    • isLoop: If true, the stack loops back to the beginning after the last card is swiped.
    • allowedSwipeDirection: Controls which directions are valid for swiping (e.g., AllowedSwipeDirection.all, AllowedSwipeDirection.left, etc.).
    • numberOfCardsDisplayed: Determines how many cards are visible in the stack at once.
    • onSwipe: A callback triggered when a user swipes. Returning false cancels the swipe.
    • onUndo: A callback triggered when an undo action is requested. Returning false cancels the undo.
    • showBackCardOnUndo: When true, swiping triggers an undo action and shows the previous card in the background.
    CardSwiper(
      cardBuilder: (index, indexFromEnd) => MyCardWidget(index),
      cardsCount: 10,
      isLoop: true,
      allowedSwipeDirection: AllowedSwipeDirection.all,
      onSwipe: (direction) {
        // Return true to allow swipe, false to cancel
        return true;
      },
    )
  6. Configure Undo functionality

    main

    The CardSwiper supports an undo mechanism to bring back the previously swiped card.

    To enable undo:

    1. Set showBackCardOnUndo to true. This ensures the previous card is visible in the background during the undo swipe.
    2. Define the undoDirection (e.g., UndoDirection.left).
    3. Use the onUndo callback to handle the logic.
    4. Adjust undoSwipeThreshold (in pixels) to control how far the user must swipe to trigger the undo action.

    Parameters:

    • showBackCardOnUndo: Whether to show the previous card in the background during undo. Defaults to false.
    • undoDirection: The direction that triggers an undo. Defaults to UndoDirection.left.
    • undoSwipeThreshold: The horizontal distance in pixels required to trigger the undo. Defaults to 50.0.
  7. Configure CardSwiper visual appearance

    main

    You can customize the visual stack effect using scale, backCardOffset, and maxAngle.

    Important Note on Scaling: To maintain a consistent back-card position when changing the scale, you must also adjust the backCardOffset.

    • A rule of thumb is that a 0.1 change in scale requires an adjustment of approximately 35px in backCardOffset.

    Parameters:

    • maxAngle: The maximum rotation angle (in degrees) the card reaches during a swipe. Must be between 0 and 360. Defaults to 30.
    • scale: The scale of the card behind the front card. Must be between 0 and 1. Defaults to 0.9.
    • backCardOffset: The Offset of the back card relative to the front card. Defaults to Offset(0, 40).
  8. Reference: CardSwiper constructor parameters

    main

    The following parameters are available for the CardSwiper constructor:

    | Parameter | Default | Description |
    |-------------------------|:--------------------------------------------------------------------|:-------------------------------------------------------------------------------------------------------------------------------------------------------------|
    | `cardBuilder` | - | Widget builder for rendering cards |
    | `cardsCount` | - | Number of cards |
    | `controller` | - | Controller to trigger swipe actions |
    | `duration` | 200 milliseconds | The duration that every animation should last |
    | `initialIndex` | 0 | Index of the first card when the swiper is initialized |
    | `isDisabled` | false | Set to `true` if swiping should be disabled, has no impact when triggered from the outside |
    | `isLoop` | true | Set to `true` if the stack should loop |
    | `maxAngle` | 30 | Maximum angle that the card can reach during swiping |
    | `allowedSwipeDirection` | AllowedSwipeDirection.all | Sets the direction in which the card can be swiped. It can be set to any combination of left, right up or down. |
    | `numberOfCardsDisplayed` | 2 | Number of cards displayed at the same time |
    | `onEnd` | - | Callback when there are no more cards left to swipe |
    | `onSwipe` | - | Callback when the user swipes a card. If the function returns `false`, the swipe action is canceled. If it returns `true`, the swipe action is performed as expected |
    | `onTapDisabled` | - | Callback when a card is tapped and `isDisabled` is `true` |
    | `onUndo` | - | Callback when the controller calls undo. If the function returns `false`, the undo action is canceled. If it returns `true`, the undo action is performed as expected |
    | `padding` | EdgeInsets.symmetric(horizontal: 20, vertical: 25) | The padding around the swiper |
    | `scale` | 0.9 | Scale of the card that is behind the front card |
    | `threshold` | 50 | Threshold from which the card is swiped away |
    | `onSwipeDirectionChange` | - | A callback containing the horizontal and vertical swipe direction |
    | `showBackCardOnUndo` | - | If true, the previous card will be shown in the background when swiping, and the swipe action will trigger an undo |
    | `undoSwipeThreshold` | 50 | The horizontal swipe distance threshold, in pixels, after which the back card switches to the previous card. Only active when showBackCardOnUndo is true |
    | `undoDirection` | UndoDirection.left | The direction of the swipe to trigger an undo |
  9. Reference: CardSwiperController methods

    main

    The CardSwiperController provides the following methods to interact with the swiper stack:

    | Method | Description |
    | ----------- | :--------------------------------------------- |
    | `swipe` | Swipes the card to a specific direction. |
    | `undo` | Bring back the last card that was swiped away. |
    | `moveTo` | Change the top card to a specific index. |
  10. Use the CardSwiper widget

    main

    The CardSwiper widget is the primary component for creating a card stack UI that users can swipe. It requires a cardBuilder to define the appearance of each card and a cardsCount to define the total number of cards in the stack.

    Key Configuration Options

    • cardBuilder: A function that returns a widget for a given index. It provides the index, build context, and drag ratios (vertical and horizontal) relative to the threshold.
    • cardsCount: The total number of cards (must be > 0).
    • initialIndex: The starting card index (defaults to 0).
    • controller: An optional CardSwiperController for programmatic control.
    • isLoop: If true, swiping the last card returns the user to the first card (defaults to true).
    • numberOfCardsDisplayed: How many cards are visible in the stack (defaults to 2).
    • threshold: The percentage of card width (1-100) required to trigger a swipe (defaults to 50).
    • scale: The scale of the card behind the front card (defaults to 0.9).
    • backCardOffset: The position offset of the back card (defaults to Offset(0, 40)).

    Callbacks

    • onSwipe: Triggered when a swipe is performed. Returning false cancels the swipe.
    • onEnd: Triggered when no more cards are left to swipe.
    • onUndo: Triggered when an undo action is performed. Returning false cancels the undo.
    • onSwipeDirectionChange: Triggered when the detected swipe direction changes.
    CardSwiper(
      cardsCount: 10,
      cardBuilder: (index, context, verticalDragRatio, horizontalDragRatio) {
        return MyCardWidget(index);
      },
      onSwipe: (oldIndex, currentIndex, direction) {
        // Handle swipe
        return true;
      },
    )
  11. Use CardSwiperDirection to represent swipe directions

    main

    The CardSwiperDirection class represents the direction of a card swipe using an angle in degrees. The angle follows a clockwise rotation:

    • 0°: Top
    • 90°: Right
    • 180°: Bottom
    • 270°: Left

    Standard Directions

    You can use the following static constants for cardinal directions:

    • CardSwiperDirection.top (0°)
    • CardSwiperDirection.right (90°)
    • CardSwiperDirection.bottom (180°)
    • CardSwiperDirection.left (270°)
    • CardSwiperDirection.none (Infinity)

    Custom Directions

    You can create custom directions (e.g., diagonal swipes) using CardSwiperDirection.custom(angle, {String? name}). Angles are automatically normalized to the [0, 360) range.

    Direction Comparison and Properties

    • isCloseTo(other, {double tolerance = 5}): Checks if a direction is approximately equal to another within a specified degree tolerance.
    • isHorizontal: Returns true if the direction is approximately left or right.
    • isVertical: Returns true if the direction is approximately top or bottom.
    // Using standard directions
    final direction = CardSwiperDirection.right;
    
    // Creating a custom diagonal direction
    final diagonal = CardSwiperDirection.custom(45); // top-right
    
    // Checking properties
    if (direction.isHorizontal) {
      print('Swiped horizontally');
    }
    
    // Comparing directions with tolerance
    if (diagonal.isCloseTo(CardSwiperDirection.custom(40), tolerance: 10)) {
      print('Close enough!');
    }