Adam gh
Adam gh

Reputation: 1

How can I get the index in PageView Flutter

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,
            )
          ],
        ),
      ),
    );
  }

Upvotes: 0

Views: 1066

Answers (3)

Hello world
Hello world

Reputation: 24

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

Upvotes: 0

Abdallah A. Odeh
Abdallah A. Odeh

Reputation: 1792

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

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

Upvotes: 1

Md. Yeasin Sheikh
Md. Yeasin Sheikh

Reputation: 63624

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

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

Upvotes: 1

Related Questions