Flutter:Curved Navigation Bar页面导航及点击无响应问题求助
核心问题分析
- 图标未切换状态:没有维护当前选中的索引状态,CurvedNavigationBar无法识别激活按钮,自然不会更新图标样式。
- 点击无反应:使用
Navigator.pushNamed会将新页面压入路由栈,若路由未正确注册会导致无响应;且这种跳转逻辑不符合底部导航栏「切换页面内容」的常规用法,通常应在同一个Scaffold内切换body内容,而非跳转新页面。
修改后的代码示例
import 'package:flutter/material.dart'; import 'package:hexcolor/hexcolor.dart'; class BAR extends StatefulWidget { const BAR({super.key}); @override State<BAR> createState() => _BARState(); } class _BARState extends State<BAR> { // 维护当前选中的导航栏索引 int _currentIndex = 0; // 对应导航项的页面内容 final List<Widget> _pages = [ const Center(child: Text("首页")), const Center(child: Text("收藏页")), const Center(child: Text("设置页")), ]; @override Widget build(BuildContext context) { return Scaffold( body: _pages[_currentIndex], // 根据索引切换显示页面 bottomNavigationBar: CurvedNavigationBar( backgroundColor: HexColor("#F7ECCD"), color: HexColor("#AE621C"), index: _currentIndex, // 指定当前选中项,让导航栏自动高亮 items: [ Icon( Icons.home, color: _currentIndex == 0 ? HexColor("#AE621C") : Colors.white, size: 30, ), Icon( Icons.favorite, color: _currentIndex == 1 ? HexColor("#AE621C") : Colors.white, size: 30, ), Icon( Icons.settings, color: _currentIndex == 2 ? HexColor("#AE621C") : Colors.white, size: 30, ) ], onTap: (index) { setState(() { _currentIndex = index; // 若坚持使用路由跳转,请确保路由已注册并改用pushReplacementNamed避免栈叠加 // switch(index) { // case 0: // Navigator.pushReplacementNamed(context, '/'); // break; // case 1: // Navigator.pushReplacementNamed(context, '/one'); // break; // case 2: // Navigator.pushReplacementNamed(context, '/two'); // break; // } }); }, ), ); } }
关键修改点说明
- 添加
_currentIndex变量跟踪选中状态,赋值给CurvedNavigationBar的index参数,让导航栏自动处理按钮高亮。 - 根据
_currentIndex动态修改图标颜色,实现选中/未选中的视觉区分。 - 使用Scaffold的body配合页面列表切换内容,这是底部导航栏的标准用法,避免路由栈叠加导致的返回逻辑混乱。
- 若必须使用路由跳转,需确保在MaterialApp的
routes中注册对应页面,并改用Navigator.pushReplacementNamed替换当前页面,防止栈内积累过多页面。
额外检查项
- 确认
hexcolor包已正确安装并导入。 - 若使用路由跳转,检查MaterialApp的路由配置:
MaterialApp( initialRoute: '/', routes: { '/': (context) => const HomePage(), '/one': (context) => const FavoritePage(), '/two': (context) => const SettingsPage(), }, )
内容的提问来源于stack exchange,提问作者GUN10010
相关产品推荐
相关产品推荐

