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

Flutter中BottomNavigationBarItem选中状态颜色不切换问题求助

解决Flutter BottomNavigationBarItem选中/取消选中时颜色不变化的问题

问题出在你没有给BottomNavigationBar设置currentIndex属性,它无法识别当前选中的页面索引,所以默认始终保持第一个item的选中状态(蓝色)。

只需要在BottomNavigationBar中添加currentIndex: _pageIndex,就能让它根据_pageIndex的变化自动切换选中项的颜色:

修改后的完整代码:

import 'package:flutter/material.dart';
import 'package:only_johns_lower_sdk/views/screens/nav_screens.dart/home_screen.dart';
import 'package:only_johns_lower_sdk/views/screens/nav_screens.dart/profile_screen.dart';
import 'package:only_johns_lower_sdk/views/screens/nav_screens.dart/users_screen.dart';


class MainPage extends StatefulWidget {
  const MainPage({super.key});

  @override
  State<MainPage> createState() => _MainPageState();
}



class _MainPageState extends State<MainPage> {

  int _pageIndex = 0;

final List<Widget> _pages = [
  const HomeScreen(),
  const ProfileScreen(),
  const UsersScreen()
  
];

  void _onItemTapped(index) {
   setState(() {
            _pageIndex = index;
          });
}
  @override
  Widget build(BuildContext context) {
    return  Scaffold(
      body: _pages[_pageIndex],
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: _pageIndex, // 新增这一行
        selectedItemColor: Colors.blue,
        unselectedItemColor: Colors.grey,
        onTap: _onItemTapped,
        items: const [
        BottomNavigationBarItem(icon: Icon(Icons.home), label: 'Home'),
        BottomNavigationBarItem(icon: Icon(Icons.person), label: 'Profile'),
        BottomNavigationBarItem(icon: Icon(Icons.person_search), label: 'Johns'),
      ],),

      
    );
    
    
  }
}

核心说明:

  • currentIndex是BottomNavigationBar的核心参数,用于指定当前选中的item索引
  • 当你通过_onItemTapped更新_pageIndex时,setState触发UI重建,BottomNavigationBar会根据新的currentIndex自动切换选中项的颜色

内容的提问来源于stack exchange,提问作者The Synergist

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 05:11:16