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

Flutter:Curved Navigation Bar页面导航及点击无响应问题求助

问题解决:Curved Navigation Bar点击无反应+图标不切换状态

核心问题分析

  1. 图标未切换状态:没有维护当前选中的索引状态,CurvedNavigationBar无法识别激活按钮,自然不会更新图标样式。
  2. 点击无反应:使用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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 06:45:45