I have 3 screens - home
, friends
and profile
. I want an AppBar
and BottomNavigationBar
to be always present in all my screens. Right now, I have the AppBar
and BottomNavigationBar
defined inside a Scaffold
in the main.dart
file. Whenever an option is tapped on BottomNavigationBar
, the Scaffold
body is replaced with the content of the screen of choice.
main.dart:
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(),
body: SafeArea(
child: Container(
child: _pageOptions[_selectedPage],
),
),
bottomNavigationBar: BottomNavigationBar(
currentIndex: _selectedPage,
onTap: (int index) {
setState(() {
_selectedPage = index;
});
},
items: [
BottomNavigationBarItem(
icon: Icon(Icons.home), title: Text('Home')),
BottomNavigationBarItem(
icon: Icon(Icons.people), title: Text('Friends')),
BottomNavigationBarItem(
icon: Icon(Icons.person), title: Text('Profile'))
],
),
),
routes: <String, WidgetBuilder>{
'/home': (BuildContext context) => Home(),
'/friends': (BuildContext context) => Friends(),
},
);
}
Now, I have a custom avatar
widget that I have reused in home
screen. On clicking the avatar
, I want to display the friends
screen. I tried this code inside an onTap
method in avatar
:
{Navigator.pushNamed(context, '/friends')},
friends.dart:
Widget build(BuildContext context) {
return Container(
child: Text('Friends'),
);
}
On tapping avatar
, I am getting the friends
screen, but everything else is lost (AppBar
, BottomNavigationBar
etc).
How do I achieve this? Should I be returning a scaffold with AppBar
, BottomNavigationBar
etc. from all 3 of my screens? Does that negatively affect performance? Or is there a way to do this just by replacing the body of the Scaffold
in main.dart
?