优化后的代码:

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;
  }
}

优化点:

  1. 去除无用的 _defaultColor_activeColor 变量。

  2. _bottomItem 方法中的 context 参数去除,因为在方法内部并没有使用到。

  3. _bottomItem 方法中,根据当前选中的索引来动态设置 icon 的颜色,去除了 _defaultColor_activeColor 变量的依赖。

  4. onTap 方法中的 setState 改为箭头函数的简写形式。

  5. 简化 exitApp 方法中的 Future.value 的调用。

代码优化后的优势

  • 代码结构更简洁,易于理解和维护。
  • 提高代码效率,减少不必要的代码执行。
  • 增强代码可读性,方便其他开发者理解代码逻辑。
Flutter 代码优化:简化导航栏和页面切换

原文地址: https://www.cveoy.top/t/topic/mKn5 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录