In Flutter, a BottomNavigationBar widget is commonly used for creating a bottom navigation bar in an app, allowing users to navigate between different pages. Below is an example of how to implement a simple BottomNavigationBar in Flutter:
Step-by-Step Implementation
Create a Stateful Widget: Since the bottom navigation bar usually interacts with the app state (like switching between pages), it's typically implemented within a StatefulWidget.
Define the Bottom Navigation Bar Items: Specify the items you want in your bottom navigation bar.
Handle Navigation: Update the page content based on the selected item.
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomeScreen(),
);
}
}
class HomeScreen extends StatefulWidget {
@override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
int _currentIndex = 0;
// List of widgets for each page
final List<Widget> _pages = [
HomePage(),
SearchPage(),
ProfilePage(),
];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Bottom Navigation Bar Example'),
),
body: _pages[_currentIndex], // Display the selected page
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',
),
],
),
);
}
}
// Example pages
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'),
);
}
}
Key Components:
- BottomNavigationBar Widget: The primary widget for creating a bottom navigation bar.
- BottomNavigationBarItem: Represents each item in the bar.
- currentIndex: Keeps track of the currently selected tab.
- onTap: Handles the tap event to switch between different pages.
Customization:
You can customize the BottomNavigationBar further by changing the colors, adding more items, adjusting the icon size, or using a custom widget for the items.
Top comments (0)