To implement a navigation bar for user to navigate between views in Flutter, we can use a Material Widget called BottomNavigationBar.
The BottomNavigationBar is usually used as tha argument of Scaffold.bottomNavigationBar.
Guidance
Material design guidance suggests that BottomNavigationBar should have no more than 5 items.
Style
The bottom navigation bar's type changes how its items are displayed. If not specified, then it's automatically set to BottomNavigationBarType.fixed when there are less than four items, and BottomNavigationBarType.shifting otherwise.
Example
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
/// Main application
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
static const String _title = 'App title';
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: _title,
home: MyStatefulWidget(),
);
}
}
/// The stateful widget that the main application instantiates.
class MyStatefulWidget extends StatefulWidget {
const MyStatefulWidget({Key? key}) : super(key: key);
@override
State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
int _selectedIndex = 0;
static const List<Widget> _widgetOptions = <Widget>[
Text('Index 0: Home'),
Text('Index 1: Business'),
Text('Index 2: School'),
];
void _onItemTapped(int index) {
setState(() {
_selectedIndex = index;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('App with BottomNavBar'),
),
body: Center(
child: _widgetOptions.elementAt(_selectedIndex),
),
bottomNavigationBar: BottomNavigationBar(
currentIndex: _selectedIndex,
unselectedItemColor: Colors.blue,
selectedItemColor: Colors.black,
onTap: _onItemTapped,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: 'Home',
),
BottomNavigationBarItem(
icon: Icon(Icons.business),
label: 'Business',
),
BottomNavigationBarItem(
icon: Icon(Icons.school),
label: 'School',
),
],
),
);
}
}
Tips
However, switching between views would dispose and rebuild the widgets. It means the status of each view cannot be retained when being switched away. A solution for this is to use IndexedStack. I will write another article on how to use IndexedStack. You may also want to explore it by reading this.
Top comments (0)