Reputation: 35
I've got a simple custom AppBar with the following code (I've taken out some code for simplification. It's not necessary for the question.):
class SimpleAppBarPageState extends StatelessWidget implements PreferredSizeWidget {
@override
Size get preferredSize => const Size.fromHeight(100);
@override
Widget build(BuildContext context) => DefaultTabController(
length: 2,
child: Scaffold(
appBar: AppBar(
...
bottom: TabBar(
isScrollable: true,
indicatorColor: Colors.white,
indicatorWeight: 5,
tabs: [
Tab(child: Text('1',
style: TextStyle(
fontWeight: FontWeight.w700,
fontSize: 20,
),
),
),
Tab(child: Text('2',
style: TextStyle(
fontWeight: FontWeight.w700,
fontSize: 20,
),
),
)
],
),
elevation: 20,
titleSpacing: 20,
),
body: TabBarView(
children: [
buildPageOne(),
buildPageTwo()
],
),
),
);
Now I have two dart files of which one contains the code for Page one and the other file contains the code for page two.
Now I want page one to be open when Tab '1' is selected and page two should be open when Tab '2' is selected.
Therefor I thought of defining a new Widget which opens the corresponding page. Here are my thoughts:
Widget buildPageOne() {
Navigator.of(context)
.push(
MaterialPageRoute(
builder: (context) => PageOne()
),
);
}
I think this last code sample is complete useless, but it kind of shows my intention what should happen.
Can you guys help me out to solve this problem?
I'd be very happy about an answer! Greetings
Upvotes: 1
Views: 164
Reputation: 3557
First of all don't use Navigator if you are using Tabs. Second you need a TabController to handle your Tabs e.g. you can use the DefaultTabController. With TabBar you can set the text/icon of each tab below the Appbar. Within your TabBarView you set your Widgets you want to display. In your case omit the Navigator and just provide the Widgets you want to display in TabBarView
DefaultTabController(
length: 2,
child: Scaffold(
appBar: AppBar(
title: 'Tabs',
bottom: TabBar(
tabs:[
Tab(icon: Icon(Icons.home)),
Tab(icon: Icon(Icons.settings)),
],
),
),
body: TabBarView(
children: [
Widget1(),
Widget2()
]
),
),
);
Upvotes: 2
Reputation: 353
Don't use methods to navigator to new screen. Create 2 separate stateless or statefull widgets: Widget1(), Widget2(),
And in childrens of TabBarView use these 2 widgets as children.
body: TabBarView(
children: [
Widget1(),
Widget2(),
],
),
Save them, do a hot restart
Upvotes: 0