Roc Boronat
Roc Boronat

Reputation: 12141

Listen to all events on Flutter's TabController

If you want to know when the user changed the tab page you can use the regular TabController.addListener() method. But what about knowing all the user events, like, for example, the user started to scroll to another page?

I need to know when the user starts scrolling to a new page. Knowing that the user already scrolled to a new page is too late.

Is there any way to achieve it?

Upvotes: 2

Views: 4282

Answers (2)

alireza daryani
alireza daryani

Reputation: 835

simple detection will be like below:

tabBarController =
    TabController(length: 5, initialIndex: pageNumber, vsync: this);
tabBarController.addListener(() {
  changePage(tabBarController.index);
});

Upvotes: 1

Mohammed Alfateh
Mohammed Alfateh

Reputation: 3524

Adding a listener to the tabController will only listen to the tab index change but to listen to the changing value (the index in double) you can add the listener to the animation of the tabController.

Here a full code, I am using flutter_hooks to create the tabController.

class TestTabListener extends HookWidget {
  const TestTabListener();

  @override
  Widget build(BuildContext context) {
    final tabController = useTabController(initialLength: 3);

    tabController.animation!.addListener(() {
      if (tabController.animation!.value != tabController.index) {
        {
          //code
          print("runing");
        }
      }
    });

    return Scaffold(
      body: TabBarView(
        controller: tabController,
        children: pages,
      ),
    );
  }

  static final pages = [
    Container(color: Colors.red),
    Container(color: Colors.black),
    Container(color: Colors.blue),
  ];
}

Be careful using a function here because it will be called multiple times, you might add condition.

Upvotes: 6

Related Questions