Reverse Index Swipe on card_swiper in flutter

75 views Asked by At

I'm using card_swiper, and I can't find the way to invert vertical index swipe. I'm getting index 0,1,2,3... when moving to up, and lasts index when moving to down. I need this inverted, get 4,3,2,1,0 starting at 0, when moving to down. I know there should be a simple solution to this, even built into the package, but I can't find it. I tried changing axisDirection:AxisDirection.down, from the name seemed to do this, but it doesn't.

Swiper(
  onIndexChanged: (int index) {
    _currentIndex = index;
    if (index == reelDataList!.length - 1) {
      fetchReelDataList();
      _updateSwipingSpeed();
    }
  },
  scrollDirection: Axis.vertical,
  itemCount: reelDataList!.length,
  index: _currentIndex,
  loop: false,
  itemBuilder: (context, index) {},
)
1

There are 1 answers

3
Yakubu On

The Swiper widget's built-in functionality does not directly support this specific behavior, so you'll have to manually manage the index and possibly use additional state to track the direction of the swipe.

to achieve 5,4,3,2,1.0,1,2,3,4,5, try

class YourWidgetState extends State<YourWidget> {
  int _currentIndex = 0; // Starting index
  bool _isSwipingUp = false; // Track swipe direction

  @override
  Widget build(BuildContext context) {
    return Swiper(
      onIndexChanged: (int index) {
        if (index > _currentIndex) {
          // Swiping up
          _isSwipingUp = true;
          if (_currentIndex == 0 && index == reelDataList!.length - 1) {
            // Special case: Wrap from 0 to the end
            _currentIndex = 1; // Move to the second item
          } else {
            _currentIndex = index;
          }
        } else {
          // Swiping down
          _isSwipingUp = false;
          if (_currentIndex == reelDataList!.length - 1 && index == 0) {
            // Special case: Wrap from the end to 0
            _currentIndex = reelDataList!.length - 2; // Move to the second last item
          } else {
            _currentIndex = index;
          }
        }
      },
      scrollDirection: Axis.vertical,
      itemCount: reelDataList!.length,
      index: _currentIndex,
      loop: false,
      itemBuilder: (context, index) {
        // Use _currentIndex to build your widgets since the index parameter might not reflect the custom logic
        return YourItemWidget(reelDataList![_currentIndex]);
      },
    );
  }
}