优化flutter的代码class NavigatorPage extends StatefulWidget const NavigatorPageKey key superkey key; override State createState = _NavigatorPageState;class _NavigatorPageState extends StateNavigatorPa
优化后的代码:
class NavigatorPage extends StatefulWidget { const NavigatorPage({Key? key}) : super(key: key);
@override State createState() => _NavigatorPageState(); }
class _NavigatorPageState extends State
@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
优化点:
1.去除无用的 _defaultColor 和 _activeColor 变量。
2.将 _bottomItem 方法中的 context 参数去除,因为在方法内部并没有使用到。
3.在 _bottomItem 方法中,根据当前选中的索引来动态设置 icon 的颜色,去除了 _defaultColor 和 _activeColor 变量的依赖。
4.将 onTap 方法中的 setState 改为箭头函数的简写形式。
5.简化 exitApp 方法中的 Future.value 的调用。
原文地址: http://www.cveoy.top/t/topic/biqP 著作权归作者所有。请勿转载和采集!