Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter navigate to specific tab in other page

Tags:

flutter

dart

I am trying to navigate from one page to another page and set index of a tab bar.

Here is my code in the first page:

GestureDetector(
onTap: () { Navigator.push(
context,
MaterialPageRoute(builder: (context) => ProductPage()),
); },
child: Container(
color: Colors.blueGrey,
)),

And in the other page (ProductPage):

class ProductPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
return DefaultTabController(
    length: 3,
    child: Scaffold(
      appBar: AppBar(
    backgroundColor: Color.fromRGBO(65,102,60,1,
    ),
        bottom: TabBar(
          isScrollable: true,
          indicatorColor: Colors.white,
          tabs: [
            Tab(icon: Text('First')),
            Tab(icon: Text('Second')),
            Tab(icon: Text('Third')),
          ],
        ),
      ),
      body: TabBarView(
        children: [
          FirstTab(),
          SecondTab(),
          ThirdTab(),
        ],
      ),
    ),
);
  }
}

Now it always opens the first tab but I want it to open SecondTab.

I have tried this:

MaterialPageRoute(builder: (context) => ProductPage(SecondTab)),

But it doesn’t work. How can I do to fix this?

like image 505
Mat Koffman Avatar asked Nov 22 '19 13:11

Mat Koffman


1 Answers

You can pass as argument an index and then use it in the initialindex of the defaultTabController.

Try something like this:

GestureDetector(
    onTap: () { Navigator.push(context,
        MaterialPageRoute(builder: (context) => ProductPage(0))); 
    },
    child: Container(color: Colors.blueGrey)
)

And in the other page (ProductPage):

class ProductPage extends StatelessWidget {
  int selectedPage;
  ProductPage(this.selectedPage);

  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      initialIndex:selectedPage,
      length: 3,
      child: Scaffold(
        appBar: AppBar(
          backgroundColor: Color.fromRGBO(65,102,60,1),
        ),
        bottom: TabBar(
          isScrollable: true,
          indicatorColor: Colors.white,
          tabs: [
            Tab(icon: Text('First')),
            Tab(icon: Text('Second')),
            Tab(icon: Text('Third')),
          ],
        ),
        body: TabBarView(
          children: [
            FirstTab(),
            SecondTab(),
            ThirdTab(),
          ],
        ),
      ),
    );
  }
}

Now you can just pass 0,1 or 2 as selected index.

like image 56
Cristian Bregant Avatar answered Oct 26 '22 03:10

Cristian Bregant