一、 创建 BottomNavigationBar
@override
Widget build(BuildContext context) {
return Scaffold(
bottomNavigationBar: BottomNavigationBar(
items: const [
BottomNavigationBarItem(
icon: Icon(Icons.chat),
label: '微信',
),
BottomNavigationBarItem(
icon: Icon(Icons.contact_mail),
label: '通讯录',
),
BottomNavigationBarItem(
icon: Icon(Icons.nature_people),
label: '发现',
),
BottomNavigationBarItem(
icon: Icon(Icons.settings),
label: '我',
),
],
),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
bottomNavigationBar: BottomNavigationBar(
selectedItemColor: Colors.green,
unselectedItemColor: Colors.grey,
...
),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
selectedItemColor: Colors.green,
unselectedItemColor: Colors.grey,
...
),
);
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key}) : super(key: key);
@override
State<StatefulWidget> createState() {
return _MyHomePageDataSource();
}
}
class _MyHomePageDataSource extends State<MyHomePage> {
int _selectedTab = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
bottomNavigationBar: BottomNavigationBar(
...
currentIndex: _selectedTab,
onTap: (idx) {
setState(() {
_selectedTab = idx;
});
},
...
),
);
}
}
class _MyHomePageDataSource extends State<MyHomePage> {
int _selectedTab = 0;
final List<Widget> _pages = [MessagePage(), ContactsPage(), MommentPage(), MinePage()];
@override
Widget build(BuildContext context) {
return Scaffold(
body: _pages[_selectedTab],// 切换页面
bottomNavigationBar: BottomNavigationBar(
...
currentIndex: _selectedTab,
onTap: (idx) {
setState(() {
_selectedTab = idx; // 切换选中标签
});
},
...
),
);
}
}