Without further ado, let's go to the code:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Bottom Navigation Bar',
theme: ThemeData(
primaryColor: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _currentIndex = 0;
final List<Widget> _pages = [
HomePage(),
SearchPage(),
ProfilePage(),
];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Bottom Navigation Bar'),
),
body: _pages[_currentIndex],
bottomNavigationBar: BottomNavigationBar(
currentIndex: _currentIndex,
onTap: (index) {
setState(() {
_currentIndex = index;
});
},
items: [
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: 'Home',
),
BottomNavigationBarItem(
icon: Icon(Icons.search),
label: 'Search',
),
BottomNavigationBarItem(
icon: Icon(Icons.person),
label: 'Profile',
),
],
),
);
}
}
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Center(
child: Text('Home Page'),
);
}
}
class SearchPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Center(
child: Text('Search Page'),
);
}
}
class ProfilePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Center(
child: Text('Profile Page'),
);
}
}
In the above example, we created a MyHomePage
widget which is StatefulWidget
. MyHomePage
Contains bottom navigation bar and related page content. Through BottomNavigationBar
the and currentIndex
properties, we can control the currently selected navigation item and onTap
update the state in the callback.
In items
the properties we set three BottomNavigationBarItem
, each with an icon and label. When the user toggles the navigation item, onTap
the callback updates currentIndex
the value, which is then used to display the corresponding page.
In the example, we created three simple pages ( HomePage
, , SearchPage
and ProfilePage
) that you can customize the content of these pages according to your needs.
Hope this example helps you!