Nimish David Mathew
Nimish David Mathew

Reputation: 3168

What is the best way to implement screens that always have AppBar and BottomNavigationBar?

I have 3 screens - home, friends and profile. I want an AppBarand 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?

Upvotes: 1

Views: 765

Answers (1)

Braj
Braj

Reputation: 626

Yes you need to return a scaffold with an appbar in all the three screens. You can put the appbar in a separate statelesswidget class and use it in all the three scaffolds. Same for bottom navigation bar. You can try to keep the returning widget in build method 'const'. Will not be possible for appbar since title will be varying. It won't get rebuilt so no worries on performance.

Upvotes: 1

Related Questions