EliaTolin
EliaTolin

Reputation: 648

Which is the best method for use route with BottomNavigatorBar?

I'm new in flutter. I create my first app with BottomNavigationBar and i would like use it for navigate in the pages.

But which is the best method for navigate?

This is my widget.

BottomNavigationBar buildBottomNavigationBar() {
return BottomNavigationBar(
  showSelectedLabels: true,
  showUnselectedLabels: false,
  currentIndex: _selectedIndex,
  items: const <BottomNavigationBarItem>[
    BottomNavigationBarItem(
        icon: Icon(Icons.addchart_outlined), label: "Dati contagi"),
    BottomNavigationBarItem(icon: Icon(Icons.coronavirus), label: "Home"),
    BottomNavigationBarItem(
      icon: Icon(Icons.help),
      label: "Info",
    ),
  ],
  selectedItemColor: Colors.blue,
  onTap: _onItemTapped,
);

}

this is _onItemTapped:

  void _onItemTapped(int index) {
setState(() {
  if (_selectedIndex != index) {
    _selectedIndex = index;
    Navigator.pushNamed(context, SVConst.allRoute[_selectedIndex]);
  }
});

}

this is SVConst.allRoute:

static const List<String> allRoute = <String>[
InfoViewRoute,
HomeViewRoute,
SettingsViewRoute,

];

But it no works perfectly.

You have suggest for me?

Upvotes: 1

Views: 41

Answers (1)

Michael Soliman
Michael Soliman

Reputation: 2818

You can create a Main Page which have the BottomNavigationBar and inject the widgets -or Scaffolds- in each tab.

adding to your Code from Flutter Docs:

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

static const TextStyle optionStyle =
      TextStyle(fontSize: 30, fontWeight: FontWeight.bold);

static const List<Widget> _widgetOptions = <Widget>[
    Text(
      'Index 0: Home',
      style: optionStyle,
    ),
    Text(
      'Index 1: Business',
      style: optionStyle,
    ),
    Text(
      'Index 2: School',
      style: optionStyle,
    ),
    Text(
      'Index 3: Settings',
      style: optionStyle,
    ),
  ];

@override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('BottomNavigationBar Sample'),
      ),
      body: Center(
        child: _widgetOptions.elementAt(_selectedIndex),
      ),
      bottomNavigationBar: // your bottomNavigationBar

Check this link it has great examples :D
Flutter Gallery - BottomNavigationDemo

Upvotes: 1

Related Questions