skip to Main Content

Im trying to implement a carousel animation in Flutter where items smoothly transition from the top left or top right to the center of the screen as the user swipes left or right through the carousel how can i achieve this in Flutter.

Carousel with animation like this enter image description here

2

Answers


  1. Chosen as BEST ANSWER

    Heres the solution.

    class AnimatedPages extends StatelessWidget {
    final PageController pageController;
    final double pageValue;
    final ChildBuilder child;
    final int pageCount;
    final OnPageChangeCallback onPageChangeCallback;
    
    const AnimatedPages({
    Key? key,
    required this.pageController,
    required this.pageValue,
    required this.child,
    required this.pageCount,
    required this.onPageChangeCallback,
    }) : super(key: key);
    
    @override
    Widget build(BuildContext context) {
    return PageView.builder(
      onPageChanged: onPageChangeCallback,
      physics: const NeverScrollableScrollPhysics(),
      controller: pageController,
      itemCount: pageCount,
      itemBuilder: (context, index) {
        if (index == pageValue.floor() + 1 || index == pageValue.floor() + 2) {
          /// Right
          return Transform.translate(
            offset: Offset(0.0, -100 * (index - pageValue)),
            child: child(index, context),
          );
        } else if (index == pageValue.floor() ||
            index == pageValue.floor() - 1) {
          /// Left
          return Transform.translate(
            offset: Offset(0.0, -100 * (pageValue - index)),
            child: child(index, context),
          );
        } else {
          /// Middle
          return child(index, context);
        }
      },
      );
     }
    }
    

  2. Check out https://pub.dev/packages/infinite_carousel it has some nice features to tune your animation. You will basically need to add custom itemBuilder and use AnimatedBuilder inside of it. As animation provide ScrollController you also apply to InfiniteCarousel.builder and play with offset to make the animation you want.

    InfiniteCarousel.builder(
       itemCount: WorkoutShareTemplate.values.length,
       itemExtent: maxItemWidth,
       loop: false,
       anchor: 0.5,
       controller: _scrollController,
       itemBuilder: (context, itemIndex, _) {
          return AnimatedBuilder(
              animation: _scrollController,
              builder: (context, child) {
                 final currentOffset = maxItemWidth * itemIndex;
                 final diff = _scrollController.offset - currentOffset;
                 final carouselRatio = maxItemWidth / maxPadding;
                 final padding = (diff / carouselRatio).abs().floor();
                 // ...
              }
          );
       }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search