Flutter 代码优化:简化导航栏和页面切换
优化后的代码:
class NavigatorPage extends StatefulWidget {
const NavigatorPage({Key? key}) : super(key: key);
@override
State createState() => _NavigatorPageState();
}
class _NavigatorPageState extends State<NavigatorPage> {
final PageController _pageController = PageController();
int _currentIndex = 0;
DateTime? _lastPressedAt;
final List<Widget> _pages = [HomePage(), MePage()];
@override
Widget build(BuildContext context) {
return Scaffold(
body: WillPopScope(
onWillPop: exitApp,
child: PageView(
controller: _pageController,
onPageChanged: (int index) {
setState(() => _currentIndex = index);
},
children: _pages,
),
),
bottomNavigationBar: BottomNavigationBar(
currentIndex: _currentIndex,
selectedItemColor: ThemeModel().theme,
selectedFontSize: 12.0,
showUnselectedLabels: true,
type: BottomNavigationBarType.fixed,
items: [
_bottomItem('主页', Icons.home_filled),
_bottomItem('我的', Icons.person_outline),
],
onTap: (int index) => _pageController.jumpToPage(index),
),
);
}
BottomNavigationBarItem _bottomItem(String label, IconData icon) {
return BottomNavigationBarItem(
label: label,
icon: Icon(icon, color: _currentIndex == 0 ? ThemeModel().theme : Colors.grey),
activeIcon: Icon(icon, color: ThemeModel().theme),
);
}
Future<bool> exitApp() async {
if (_lastPressedAt == null || DateTime.now().difference(_lastPressedAt!) > Duration(seconds: 2)) {
EasyLoading.showToast('再点一次退出');
_lastPressedAt = DateTime.now();
return false;
}
return true;
}
}
优化点:
-
去除无用的
_defaultColor和_activeColor变量。 -
将
_bottomItem方法中的context参数去除,因为在方法内部并没有使用到。 -
在
_bottomItem方法中,根据当前选中的索引来动态设置icon的颜色,去除了_defaultColor和_activeColor变量的依赖。 -
将
onTap方法中的setState改为箭头函数的简写形式。 -
简化
exitApp方法中的Future.value的调用。
代码优化后的优势
- 代码结构更简洁,易于理解和维护。
- 提高代码效率,减少不必要的代码执行。
- 增强代码可读性,方便其他开发者理解代码逻辑。
原文地址: https://www.cveoy.top/t/topic/mKn5 著作权归作者所有。请勿转载和采集!