Can I use 'index' in PageView widget in other widget?
Asked Answered
M

2

5

I'm making an app divided to two sections: one(upper section) is PageView widget area, another(lower section) is Container widget area. I want the lower section to show 'we are in X page' when I change pages in the upper section.

I tried to use index of PageView widget in Container widget, but console said "undefined name 'index'". So I declared like int index; as a global variable, and tried again, but it doesn't work. I think this index is different from index of PageView widget.

import 'package:flutter/material.dart';

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  static final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  final controller = PageController(initialPage: 0);
  var scrollDirection = Axis.horizontal;
  var actionIcon = Icons.swap_vert;
  int index;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
      appBar: AppBar(
        centerTitle: true,
        title: Text('it\'s a drill for page view'),
      ),
      body: _buildBody(),
    );
  }

  Widget _buildBody() {
    return SafeArea(
      child: Column(
        children: <Widget>[
          Expanded(
            child: PageView.builder(
              controller: controller,
              itemCount: 5,
              itemBuilder: (context, index) {
                return Text('it is ${index} page');
              },
            )
          ),
          Expanded(
            child: FittedBox(
              fit: BoxFit.fitWidth,
              child: Container(
                color: Colors.blue,
                child: Text('we are in ${index} page!'),
              ),
            ),
          )
        ],
      ),
    );
  }
}

I'm a beginner of programming, and doing this as a hobby. But I really like it. Actually I gave up my own study and career and stick to programming now. I hope you help me solve this problem. Thank you. I love you.

Microorganism answered 8/9, 2019 at 7:50 Comment(0)
A
5

yes. like controller.page for the current page.

class Sample extends StatelessWidget{

final int value;
Sample(this.value);

build(context) => Text("you are in $value");
}

and use Sample(controller.page)

EDIT: your code should be

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  static final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  final controller = PageController(initialPage: 0);
  var scrollDirection = Axis.horizontal;
  var actionIcon = Icons.swap_vert;
  int currentPage=0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
      appBar: AppBar(
        centerTitle: true,
        title: Text('it\'s a drill for page view'),
      ),
      body: _buildBody(),
    );
  }

  Widget _buildBody() {
    return SafeArea(
      child: Column(
        children: <Widget>[
          Expanded(
              child: PageView.builder(
                controller: controller,
                itemCount: 5,
                itemBuilder: (context, index) {
                  return Text('it is ${index} page');
                },
                onPageChanged: (page){
                  setState(() {
                    currentPage=page;
                  });
                },
              )
          ),
          Expanded(
            child: FittedBox(
              fit: BoxFit.fitWidth,
              child: Container(
                color: Colors.blue,
                child: Text('we are in ${currentPage} page!'),
              ),
            ),
          )
        ],
      ),
    );
  }
}
Autogenous answered 8/9, 2019 at 7:57 Comment(8)
Thank you very much! Thanks to your help, I got the result almost I wanted.Microorganism
But there are still two problems. One is Sample(controller.page) seems double. Although I declared value as int, the console says "The argument type 'double' can't be assigned to the parameter type 'int'." So I declared value as double, it worked. Unfortunately another problem comes here. When I run the emulator, it seems to work well, but it doesn't change the number(ie. 3.0 because I declared it as double) at all, when I change pages. I think that's because I made Sample class as statelessWidget, but not sureMicroorganism
use controller.page.toInt()Autogenous
for the second part you need to call setState() in your class that holds the pageview for refreshing the ui. There is function onPageChanged(int) see(api.flutter.dev/flutter/widgets/PageView-class.html) which is called on page change so call setState in hereAutogenous
I'm really sorry to make you wait. I have a lot of things to do as a student. I think I can't check your solution today. Could you give me some time?Microorganism
I wrote the code without editor so I thought if I was my code that didn't work that's allAutogenous
It doesn't work..but thank you for your sincere help. I'm using android studio.Microorganism
I finally solved this problem thanks to you! It really works perfect now. Thank you very much. I hope your day be happy! With Love.Microorganism
L
4

Just add listener to PageController like that:

  @override
  void initState() {
    super.initState();
    index = 0;
    controller.addListener(() {
      setState(() {
        index = controller.page.toInt();
      });
    });
  }
Loving answered 8/9, 2019 at 8:33 Comment(5)
Thank you for replying me. Can I ask you where PageController is? I'm terribly sorry that I'm a beginner in this programming. I think I can't check right now. Finishing something to do, I'll check.Microorganism
here he is final controller = PageController(initialPage: 0);Loving
it works perfect! Thank you very much. But it makes some time difference. the lower one follows the upper one with about 0.5 second. Any suggestion?Microorganism
Replace controller.page.toInt() with controller.page.round(), and delay will disappear.Loving
There is still some delay. I'll make a new question about that. If you're free, please come to help me to the new question.Microorganism

© 2022 - 2024 — McMap. All rights reserved.