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

Flutter NavigationBar切换时indicatorColor闪烁及选中label加粗问题求助

解决方案

1. 修复指示器闪烁问题

闪烁的根源是全局切换indicatorColor时,组件状态更新过程中出现短暂的视觉冲突。我们可以通过自定义indicator组件,精准控制每个索引对应的指示器显示:

  • 选中索引为0时,直接返回一个空容器完全隐藏指示器
  • 其他索引使用默认的彩色指示器

这种方式避免了透明色与彩色切换时的过渡闪烁,因为索引0的位置本身就没有渲染指示器。

2. 设置选中项Label加粗

利用NavigationBar的selectedLabelStyle和unselectedLabelStyle属性,直接配置文本的粗细样式:

  • 选中状态下设置字体加粗
  • 未选中状态保持默认常规粗细

修改后的完整代码

class HomeScreen extends StatelessWidget {
  const HomeScreen({Key? key, required this.navigationShell})
      : super(key: key ?? const ValueKey('ScaffoldWithNestedNavigation'));

  final StatefulNavigationShell navigationShell;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: navigationShell,
      bottomNavigationBar: NavigationBar(
        height: 80.h,
        selectedIndex: navigationShell.currentIndex,
        surfaceTintColor: Colors.white,
        backgroundColor: Colors.white,
        // 配置标签样式:选中时加粗
        selectedLabelStyle: const TextStyle(fontWeight: FontWeight.bold),
        unselectedLabelStyle: const TextStyle(fontWeight: FontWeight.normal),
        // 自定义指示器:索引0隐藏,其他显示彩色指示器
        indicator: navigationShell.currentIndex == 0
            ? const SizedBox.shrink()
            : NavigationIndicator(color: AppColors.bottomNavIconGreen),
        destinations: [
          NavigationDestination(
            label: 'Chat',
            icon: Icon(
              Icons.chat_bubble_outline,
              size: 24.h,
            ),
          ),
          NavigationDestination(
            label: 'History',
            icon: Icon(
              Icons.access_time,
              size: 24.h,
            ),
          ),
          NavigationDestination(
            label: 'Account',
            icon: Icon(
              CupertinoIcons.person_crop_circle,
              size: 24.h,
            ),
          ),
        ],
        onDestinationSelected: (index) {
          index != 0
              ? navigationShell.goBranch(
                  index,
                  initialLocation: index == navigationShell.currentIndex,
                )
              : context.pushNamed('chat');
        },
      ),
    );
  }
}

额外说明

  • 若需要给索引0的项添加选中时的图标变色效果,可在NavigationDestination的selectedIcon属性中设置对应图标
  • NavigationIndicator支持自定义形状、圆角等属性,可根据需求进一步调整样式

内容的提问来源于stack exchange,提问作者Mehedi Hasan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 21:04:52