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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With