How to achieve each screen having Scaffold widget while using BottomNavigation bar?

220 views Asked by At

I am new to flutter and recently I am implementing bottom navigation bar for the first time.

So As any of the general apps , I want to achieve a screens which can be navigated using bottom navigation bar and each screen has its own Appbar and all stuff ( in short Scaffold widget ).

But as bottom navigation bar itself is wrapped inside Scaffold and I have read somewhere that it's advisable not to nest Scaffold widgets.

So in this case , is there any alternate ways to do so or How can I achieve this ?.

Thank you :)

1

There are 1 answers

3
Abhishek Ghaskata On

you can make only one scaffold for your 3 or 4 or 5 screens

class MyStatefulWidget extends StatefulWidget {
  MyStatefulWidget({Key key}) : super(key: key);

  @override
  _MyStatefulWidgetState createState() => _MyStatefulWidgetState();
}

class _MyStatefulWidgetState extends State<MyStatefulWidget> {
  int _selectedIndex = 0;
  static const TextStyle optionStyle =
      TextStyle(fontSize: 30, fontWeight: FontWeight.bold);
  static const List<Widget> _widgetOptions = <Widget>[
     Screen1(); // this is your first screen which return let's say listview builder
     Screen2(); // this is your second screen which return let's say container
     Screen3(); // this is your third screen which return let's say gridview or column
  ];

  void _onItemTapped(int index) {
    setState(() {
      _selectedIndex = index;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('BottomNavigationBar Sample'),
      ),
      body: Center(
        child: _widgetOptions.elementAt(_selectedIndex),
      ),
      bottomNavigationBar: BottomNavigationBar(
        items: const <BottomNavigationBarItem>[
          BottomNavigationBarItem(
            icon: Icon(Icons.home),
            title: Text('Home'),
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.business),
            title: Text('Business'),
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.school),
            title: Text('School'),
          ),
        ],
        currentIndex: _selectedIndex,
        selectedItemColor: Colors.amber[800],
        onTap: _onItemTapped,
      ),
    );
  }
}

here onTap method navigates your screen. you don't need navigator.push or navigator.pushNamed to navigate the screen.