How to change the default tab while navigating in Flutter?

Viewed 15296

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.

2 Answers

You can Use Initial Index:

_tabController = new TabController(length: 3, vsync: this, initialIndex: 1);

I had similar problem. I created a file named "globals.dart".

my_app/globals.dart

library my_app.globals;

import 'package:flutter/material.dart';

TabController tabController;

And, after you set the tab controller, copy reference to this.

_homepage Class

import 'package:my_app/globals.dart' as globals;

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

    globals.tabController = _tabController;

    super.initState();
}

other_page Class

import 'package:my_app/globals.dart' as globals;

...(in any function you want)...

globals.tabController.animateTo(2);
Related