Flutter Swiper, Be on same page after poping from another screen

1.2k views Asked by At

I am using Flutter Swiper Plugin to create a swiper. On each page of the swiper, I have Buttons which take me to another screen using Navigator.of(context).pushNamed('/routeToSecondPage').

The problem I am facing is that when I come back from that page, The Swiper gets reloaded and come back to its initial page (i.e. 0). I want it to be on the same page from where the button was pressed.

I tried using PageView, it works as expected there with keepPage = true, but because of some of the features like DotIndicator, Infinite loop etc, I am more inclined towards using Flutter_swiper.

Here is my Swiper code:

class SwiperHomePage extends StatefulWidget {


@override
  _SwiperHomePageState createState() => _SwiperHomePageState();
}

class _SwiperHomePageState extends State<_SwiperHomePage> {
  static int _swiperIndex = 0;
  final SwiperController _controller = SwiperController();

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.white,
      child:Swiper(
              index: _swiperIndex,
              loop: true,
              scrollDirection: Axis.horizontal,
              indicatorLayout: PageIndicatorLayout.SCALE,
              itemBuilder: (ctx, i) {
                return Container(
                  margin: EdgeInsets.only(top: 24),
                  child: Container(
                          margin: EdgeInsets.all(4),
                          child: EachPage(),
                        ),
                );
              },
              itemCount: length,
              controller: _controller,
              pagination: SwiperPagination(
                alignment: Alignment.topCenter,
                builder: DotSwiperPaginationBuilder(
                    color: Colors.lightBlueAccent, activeColor: Colors.blue),
              ),
              duration: 1000,
              plugins: [],
            ),
    );
  }

  changeSwiperIndex(int index) {
    _controller.move(index, animation: true);
  }
}
1

There are 1 answers

0
Anirudh Bagri On

Figured out how to do this:

I was keeping _swiperIndex, but not changing it when the page was getting changed. Adding the following inside the swiper did the trick.

          onIndexChanged: (index) {
            _swiperIndex = index;
          },