You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter BottomNavigationBar点击图标变色2秒后恢复正常求助

实现BottomNavigationBar图标点击后临时高亮2秒

解决方案代码

首先在你的State类中添加状态变量,然后修改BottomNavigationBar的相关配置:

// 你的State类内部
Map<int, bool> _tempHighlighted = {};

@override
void initState() {
  super.initState();
  // 初始化所有导航项的临时高亮状态为false
  _tempHighlighted = {0: false, 1: false};
}

// 替换原有的Theme和BottomNavigationBar部分
child: Theme(
  data: ThemeData(
    splashFactory: InkRipple.splashFactory,
    splashColor: Color(0xFF009EFB),
    highlightColor: Color(0xFF009EFB),
  ),
  child: BottomNavigationBar(
    backgroundColor: Color(0xFFDADADA),
    type: BottomNavigationBarType.fixed,
    showUnselectedLabels: true,
    showSelectedLabels: true,
    currentIndex: appStore.currentIndex,
    unselectedItemColor: textSecondaryColorGlobal,
    unselectedLabelStyle: secondaryTextStyle(),
    selectedLabelStyle: secondaryTextStyle(),
    // 设置实际的选中颜色(与临时高亮颜色一致)
    selectedItemColor: Color(0xFF009EFB),
    items: [
      BottomNavigationBarItem(
        icon: cachedImage(
          'assets/hom.png',
          width: 20,
          height: 20,
          color: _tempHighlighted[0] == true
              ? Color(0xFF009EFB) // 临时高亮颜色
              : (appStore.currentIndex == 0 ? Color(0xFF009EFB) : textSecondaryColorGlobal),
        ),
        label: 'Home',
      ),
      BottomNavigationBarItem(
        icon: cachedImage(
          'assets/shop.png',
          width: 20,
          height: 20,
          color: _tempHighlighted[1] == true
              ? Color(0xFF009EFB) // 临时高亮颜色
              : (appStore.currentIndex == 1 ? Color(0xFF009EFB) : textSecondaryColorGlobal),
        ),
        label: 'Shop',
      ),
    ],
    onTap: (index) {
      // 触发临时高亮
      setState(() {
        _tempHighlighted[index] = true;
      });

      // 2秒后恢复原有状态
      Future.delayed(const Duration(seconds: 2), () {
        if (mounted) {
          setState(() {
            _tempHighlighted[index] = false;
          });
        }
      });

      // 保留原有的页面切换逻辑
      setState(() {
        appStore.currentIndex = index;
        appStore.setIndex(index);
      });

      if (appStore.currentIndex == 0) {
        webViewController!.loadUrl(urlRequest: URLRequest(url: /* 补全你的URL */));
      } else if (appStore.currentIndex == 1) {
        // 原有的页面逻辑
      }
    },
  ),
)

关键修改说明

  1. 临时状态管理:用_tempHighlighted字典记录每个导航项是否处于临时高亮状态,初始化时设置所有项为false。
  2. 图标颜色逻辑:优先判断临时高亮状态,若为true则显示选中色;否则根据currentIndex显示对应状态的颜色(选中/未选中)。
  3. 高亮触发与恢复:点击导航项时立即设置对应项为高亮状态,通过Future.delayed延迟2秒后恢复,同时加入mounted判断避免组件销毁后调用setState报错。
  4. 颜色区分:修正了原代码中selectedItemColor与unselectedItemColor相同的问题,设置实际的高亮颜色为Color(0xFF009EFB),确保视觉区分。

内容的提问来源于stack exchange,提问作者Nishant Tyagi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 03:35:29