Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the default tab while navigating in Flutter?

I have the following code for the TabBar page:

class HomePage extends StatefulWidget {


  static String tag = 'home-page';

  @override
  _homepage createState() => new _homepage();
}

class _homepage extends State<HomePage> with TickerProviderStateMixin{


  AnimationController percentageAnimationController;
  TabController _tabController;


  @override
  void initState() {
    _tabController = new TabController(length: 3, vsync: this);


    super.initState();
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {

    return new Scaffold(

        bottomNavigationBar: new Material(
          color: Colors.white,
          child: new TabBar(
              controller: _tabController,
              indicatorColor: Theme.Colors.loginGradientStart,
              labelColor: Theme.Colors.loginGradientStart,
              tabs: <Widget>[
                new Tab(
                  icon: new Icon(wind_icon),
                ),
                new Tab(
                  icon: new Icon(chart_icon),
                ),
                new Tab(
                  icon: new Icon(settings_icon),
                ),
              ]
          ),
        ),
        body:
        new TabBarView(
          children: <Widget>[

            TabOne(),

            TabTwo(),

            TabThree(),

            ],
          controller: _tabController,
        ),
    );
  }
}

Now if I navigate to this page it automatically opens the first tab but I want to open the second tab instead of the first i.e. tab index 1.

I am able to find out that we can achieve this by using _tabController.animateTo(1); but I want to know how can I do this from button press of other pages.

like image 338
Sarthak Verma Avatar asked Oct 23 '18 04:10

Sarthak Verma


1 Answers

You can Use Initial Index:

_tabController = new TabController(length: 3, vsync: this, initialIndex: 1);
like image 182
anmol.majhail Avatar answered Oct 08 '22 22:10

anmol.majhail