Home > Enterprise >  How can I get the index in PageView Flutter
How can I get the index in PageView Flutter

Time:07-12

I have a problem and don't know how to solve it, so I want to use an index in PageView and can't use PageView.builder because I have two pages one static HomeBody() and the other is not static and I need an Index for it.

final controller = PageController(initialPage: 0);

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (context) => CityData(),
      child: MaterialApp(
        home: PageView(
          controller: controller,
          children: [
            HomeBody(),
            FavoriteCityScreen(
              i: the Index,
            )
          ],
        ),
      ),
    );
  }

CodePudding user response:

FavoriteCityScreen is only visible while index is 1 on PageView. You can use FavoriteCityScreen(i: 1)

children: [
   HomeBody(),
   FavoriteCityScreen(
   i: 1, //the Index
    )
  ],

CodePudding user response:

To get the index whenever the tab is changed, add the callback onPageChanged(int index)

PageView(
  ...,
  onPageChanged: (index){
    this.index = index;
  },
),

CodePudding user response:

You can use add listener to get the page or index number. This is what I did. _pageController.addListener(() { print(_pageController.page!.round()); });

  • Related