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

Flutter中BottomNavigationBar添加5个项触发RangeError问题求助

解决Flutter BottomNavigationBar的RangeError问题

这个错误RangeError (index): Invalid value: Not in range 0..2, inclusive: 3的核心原因很明确:你的底部导航项数量和对应的页面列表数量不匹配,或者当前选中的索引超出了页面列表的有效范围。

你提到要创建5个导航项,但从错误提示来看,你用来切换显示的页面数组只有3个元素——当你点击第4个导航项(索引为3)时,程序尝试访问页面数组的第3个索引,可数组最大只有索引2,自然触发了越界错误。

修复步骤:

  • 维护一个和BottomNavigationBar.items数量完全一致的页面列表
  • 新增currentIndex变量跟踪当前选中的导航项,初始值设为0,并在onTap回调中更新这个值
  • 确保页面主体部分根据currentIndex正确显示对应页面

修正后的完整代码:

import 'package:flutter/material.dart';

void main() {
  runApp(const BottomNavDemo());
}

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

  @override
  _BottomNavDemoState createState() => _BottomNavDemoState();
}

class _BottomNavDemoState extends State<BottomNavDemo> {
  // 跟踪当前选中的导航索引,初始为0
  int _currentIndex = 0;

  // 定义5个对应页面,数量和导航项严格匹配
  final List<Widget> _pages = const [
    Center(child: Text('首页')),
    Center(child: Text('发现')),
    Center(child: Text('消息')),
    Center(child: Text('我的')),
    Center(child: Text('设置')),
  ];

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text('底部导航示例')),
        // 根据当前索引渲染对应页面
        body: _pages[_currentIndex],
        bottomNavigationBar: BottomNavigationBar(
          currentIndex: _currentIndex,
          // 5个导航项,和_pages长度完全一致
          items: const [
            BottomNavigationBarItem(icon: Icon(Icons.home), label: '首页'),
            BottomNavigationBarItem(icon: Icon(Icons.explore), label: '发现'),
            BottomNavigationBarItem(icon: Icon(Icons.message), label: '消息'),
            BottomNavigationBarItem(icon: Icon(Icons.person), label: '我的'),
            BottomNavigationBarItem(icon: Icon(Icons.settings), label: '设置'),
          ],
          // 点击导航项时更新选中索引
          onTap: (index) {
            setState(() {
              _currentIndex = index;
            });
          },
        ),
      ),
    );
  }
}

关键注意事项:

  • _pages的长度必须和BottomNavigationBar.items的长度完全对等,否则点击超出页面列表长度的导航项就会再次触发越界错误
  • 必须设置currentIndex并在onTap中更新它,这不仅能让底部导航正确显示选中状态,还能保证页面切换的逻辑正确性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:55:32