在 Flutter 中使用 NavigationRail 和 BottomNavigationBar
在Flutter中,你可以使用NavigationRail
和BottomNavigationBar
来创建一个带有侧边栏的底部导航栏应用。以下是一个简单的示例代码:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
int _selectedIndex = 0;
void _onItemTapped(int index) {
setState(() {
_selectedIndex = index;
});
}
List<Widget> _buildPages() {
return [
Icon(Icons.home),
Icon(Icons.favorite),
Icon(Icons.shopping_cart),
Icon(Icons.person),
];
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: _buildPages().elementAt(_selectedIndex),
),
bottomNavigationBar: BottomNavigationBar(
items: [
BottomNavigationBarItem(icon: Icon(Icons.home), title: Text('Home')),
BottomNavigationBarItem(icon: Icon(Icons.favorite), title: Text('Favorites')),
BottomNavigationBarItem(icon: Icon(Icons.shopping_cart), title: Text('Cart')),
BottomNavigationBarItem(icon: Icon(Icons.person), title: Text('Profile')),
],
currentIndex: _selectedIndex,
selectedItemColor: Colors.amber[800],
onTap: _onItemTapped,
),
navigationRail: NavigationRail(
selectedIndex: _selectedIndex,
onDestinationSelected: _onItemTapped,
destinations: [
NavigationRailDestination(icon: Icon(Icons.home), label: Text('Home')),
NavigationRailDestination(icon: Icon(Icons.favorite), label: Text('Favorites')),
NavigationRailDestination(icon: Icon(Icons.shopping_cart), label: Text('Cart')),
NavigationRailDestination(icon: Icon(Icons.person), label: Text('Profile')),
],
),
);
}
}
这段代码创建了一个带有NavigationRail
侧边栏和BottomNavigationBar
底部导航栏的应用。用户可以点击底部导航栏或侧边栏的项目来切换页面。_buildPages
方法返回一个包含所有页面的列表,这样
评论已关闭