Flutter 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) { // 原有的页面逻辑 } }, ), )
关键修改说明
- 临时状态管理:用
_tempHighlighted字典记录每个导航项是否处于临时高亮状态,初始化时设置所有项为false。 - 图标颜色逻辑:优先判断临时高亮状态,若为
true则显示选中色;否则根据currentIndex显示对应状态的颜色(选中/未选中)。 - 高亮触发与恢复:点击导航项时立即设置对应项为高亮状态,通过
Future.delayed延迟2秒后恢复,同时加入mounted判断避免组件销毁后调用setState报错。 - 颜色区分:修正了原代码中
selectedItemColor与unselectedItemColor相同的问题,设置实际的高亮颜色为Color(0xFF009EFB),确保视觉区分。
内容的提问来源于stack exchange,提问作者Nishant Tyagi
相关产品推荐
相关产品推荐

