Mario Ay
Mario Ay

Reputation: 11

Flutter PageView PageController from another class

How to call pageController from another class?

I create a pageController in main class, and I want to use it in the each of PageView children (widgets from another class).

Thank you.

Upvotes: 0

Views: 1265

Answers (1)

Dominic
Dominic

Reputation: 11

You could do something like this

class SomeChild extends StatelessWidget {
  final PageController controller;

  const SomeChild({Key key, this.controller}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialButton(
      onPressed: () => controller.animateToPage(1, duration: Duration(seconds: 1), curve: Curves.linear),
    );
  }
}

Then just declare this class as a child of the pageview. The material button is there just so you see how you can access the controller. Then in the class which has the pageview, you could simply pass in the controller as a parameter like this:

class SomeClass extends StatelessWidget {
  final PageController controller = PageController();

  @override
  Widget build(BuildContext context) {
    return PageView(
      controller: controller,
      children: [
        SomeChild(controller: controller),
        SomeChild(controller: controller),
        SomeChild(controller: controller),
      ],
    );
  }
}

Upvotes: 1

Related Questions