Flutter BottomNavigationBar组件使用详解,如何实现自定义底部导航栏
import 'package:flutter/material.dart';
class CustomBottomNavigationBar extends StatefulWidget {
@override
_CustomBottomNavigationBarState createState() => _CustomBottomNavigationBarState();
}
class _CustomBottomNavigationBarState extends State<CustomBottomNavigationBar> {
int _selectedIndex = 0;
static const TextStyle optionStyle =
TextStyle(fontSize: 30, fontWeight: FontWeight.bold);
// 导航控制器,用于切换页面
final _pageController = PageController(initialPage: 0);
@override
Widget build(BuildContext context) {
return Scaffold(
body: PageView(
controller: _pageController,
children: <Widget>[
Center(child: Text('Home Page')),
Center(child: Text('Favorites Page')),
Center(child: Text('Settings Page')),
],
onPageChanged: (int index) {
setState(() {
_selectedIndex = index;
});
},
),
bottomNavigationBar: BottomNavigationBar(
currentIndex: _selectedIndex,
// 导航项点击事件处理
onTap: (int index) {
setState(() {
_selectedIndex = index;
_pageController.jumpToPage(index);
});
},
items: <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.home),
title: Text('Home'),
),
BottomNavigationBarItem(
icon: Icon(Icons.favorite),
title: Text('Favorites'),
),
BottomNavigationBarItem(
icon: Icon(Icons.settings),
title: Text('Settings'),
),
],
),
);
}
}
这段代码实现了一个自定义的底部导航栏,用户可以点击底部导航栏的不同项来切换页面。同时,它使用PageView
来管理不同的页面,并在用户点击导航项时更新当前显示的页面。这个例子展示了如何在Flutter中创建一个响应用户交互的导航组件。
评论已关闭