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

Flutter开发中BottomNavigationBar底部导航栏无索引不显示如何解决

问题原因

  • 你定义的_selectedIndex选中索引、_widgetOptions页面对象数组没有和Scaffold的body属性关联,当前body为固定的背景容器,不会跟随导航点击切换内容
  • BottomNavigationBar未配置背景色和未选中项样式,容易出现图标、文字颜色和容器背景重合,导致内容不可见

修复后代码

import 'dart:ui';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';

class MyStatefulWidget extends StatefulWidget {
  const MyStatefulWidget({Key? key}) : super(key: key);

  @override
  State<MyStatefulWidget> createState() => BottomNavigation();
}

class BottomNavigation extends State<MyStatefulWidget> {
  int _selectedIndex = 0;
  final List<Widget> _widgetOptions= <Widget>[
    const Text('Home', style: optionStyle),
    const Text('Message', style: optionStyle)
  ];

  static const TextStyle optionStyle = TextStyle(fontSize: 30, fontWeight: FontWeight.bold);

  void _onItemTapped(int index) {
    setState(() {
      _selectedIndex = index;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        actions: <Widget>[
          IconButton(icon: const Icon(Icons.search), onPressed: () {}),
        ],
      ),
      // 修改body为Stack结构,底层放背景图,上层放对应页面
      body: Stack(
        children: [
          // 背景图容器保持不变
          Container(
            decoration: const BoxDecoration(
              image: DecorationImage(
                image: AssetImage("assets/OptimizeYourFood/OptimizeYourFood2.png"),
                fit: BoxFit.cover,
              ),
              color: Colors.transparent
            )
          ),
          // 显示当前选中的页面对象
          Center(
            child: _widgetOptions[_selectedIndex],
          )
        ],
      ),
      bottomNavigationBar: BottomNavigationBar(
        // 新增导航栏背景色,避免和页面背景重合
        backgroundColor: Colors.white,
        // 新增未选中项颜色,确保未选中的导航项可见
        unselectedItemColor: Colors.grey,
        items: const <BottomNavigationBarItem>[
          BottomNavigationBarItem(
            icon: Icon(Icons.local_dining),
            label: 'Reduce',
          ),
          BottomNavigationBarItem(
            icon: Icon(FontAwesomeIcons.recycle),
            label: 'Reuse and recycle',
          ),
        ],
        currentIndex: _selectedIndex,
        selectedItemColor: Colors.amber[800],
        onTap: _onItemTapped,
      ),
    );
  }
}

修改说明

  • 调整body为Stack布局,保留原有背景图的同时,渲染当前选中索引对应的页面组件,实现点击导航切换页面的效果
  • 给BottomNavigationBar补充背景色和未选中项颜色配置,解决导航栏内容看不见的问题
  • 原有的索引切换逻辑、导航项配置完全保留,无需调整其他业务逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 16:39:04