How to detect TabBar change in Flutter?

Ashtav picture Ashtav · Apr 3, 2019 · Viewed 12.4k times · Source

I need to detect TabBar when I swipe then print somethings on console, how I can do that? This is my code.

bottomNavigationBar: new Material(
             color: Colors.blueAccent,
             child: new TabBar(
               onTap: (int index){ setState(() {
                 _onTap(index);
               });},

               indicatorColor: Colors.white,
               controller: controller,
               tabs: <Widget>[
                 new Tab(icon: new Icon(Icons.shopping_basket)),
                 new Tab(icon: new Icon(Icons.store)),
                 new Tab(icon: new Icon(Icons.local_offer)),
                 new Tab(icon: new Icon(Icons.assignment)),
                 new Tab(icon: new Icon(Icons.settings)),

               ],
             )
           ),

Answer

nonybrighto picture nonybrighto · Apr 3, 2019

You need to add a listener to your tab controller - maybe in initState.

controller.addListener((){
   print('my index is'+ controller.index.toString());
});