我正试图在我的Ffltter应用程序中添加一个侧边菜单和一个底部导航栏.我已经将代码合并到main_creen.dart文件中.

当我运行代码时,底部导航栏工作正常,但如果我点击侧边菜单项,我会收到以下错误:

_AssertionError ('package:flutter/src/material/bottom_navigation_bar.dart': Failed assertion: line 251 pos 15: '0 <= currentIndex && currentIndex < items.length': is not true.)

以下是main_creen.dart代码:

 class MainScreenState extends State<MainScreen> {
  final auth = FirebaseAuth.instance;
  int _pageIndex = 0;

  final List<Widget> appScreens = [
    const CompanyDashboardScreen(),
    const TransactionDetailScreen(true),
    const AppointmentCalendarScreen(),
    const UserProfileScreen(),
    const ChatScreen(),
    const CompanyScreen(),
    const UserProfileScreen(),
  ];

  Future<void> signOut() async {
    await auth.signOut();
  }

  void onItemTapped(int index) {
    setState(() {
      _pageIndex = index;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CustomAppBar(),
      body: Container(child: appScreens[_pageIndex]),
      drawer: Drawer(
        child: (ListView(
          padding: EdgeInsets.zero,
          children: [
            const UserAccountsDrawerHeader(
              accountName: Text('Billy Bob Baker'),
              accountEmail: Text('billy.bob.baker@gmail.com'),
            ),
            Container(
              child: Column(
                children: <Widget>[
                  ListTile(
                    title: const Text('Add Company'),
                    selected: _pageIndex == 5,
                    onTap: () {
                      // Update the state of the app
                      onItemTapped(5);
                      // Then close the drawer
                      Navigator.pop(context);
                    },
                  ),
                  ListTile(
                    title: const Text('Add User'),
                    selected: _pageIndex == 6,
                    onTap: () {
                      // Update the state of the app
                      onItemTapped(6);
                      // Then close the drawer
                      Navigator.pop(context);
                    },
                  ),
                  ListTile(
                    title: const Text('Log Out'),
                    selected: _pageIndex == 7,
                    onTap: () {
                      // Update the state of the app
                      signOut();
                      // Then close the drawer
                      Navigator.pop(context);
                      Navigator.push(
                          context,
                          MaterialPageRoute(
                              builder: (context) => const LoginScreen()));
                    },
                  ),
                ],
              ),
            ),
          ],
        )),
      ),
      bottomNavigationBar: BottomNavigationBar(  <<<  ERROR HERE
        backgroundColor: Colors.blueAccent,
        selectedIconTheme: const IconThemeData(color: Colors.white),
        selectedItemColor: Colors.white,
        unselectedItemColor: Colors.black45,
        type: BottomNavigationBarType.fixed,
        currentIndex: _pageIndex,
        onTap: (value) {
          setState(() {
            _pageIndex = value;
          });
        },
        items: const [
          BottomNavigationBarItem(icon: Icon(Icons.home), label: "Home"),
          BottomNavigationBarItem(
              icon: Icon(Icons.add_business_outlined), label: "Trxn"),
          BottomNavigationBarItem(
              icon: Icon(Icons.calendar_today), label: "Calendar"),
          BottomNavigationBarItem(icon: Icon(Icons.people), label: "User"),
          BottomNavigationBarItem(icon: Icon(Icons.chat), label: 'Chat'),
        ],
      ),
    );
  }

  // Added this for BottomNavigationBar sync
  void setIndex(int index) {
    if (mounted) setState(() => _pageIndex = index);
  }
}

如何在不相互干扰的情况下组合这两种导航方法?

谢谢

推荐答案

抽屉里的ListTiles可以将_pageIndex设置为5、6和7,但BottomNavigationBar中只有5个项目(最大有效索引为4).

我建议将抽屉ListTiles的逻辑与BottomNavigationBar分开.换句话说,不要让抽屉更新页面索引.相反,点击抽屉中的瓷砖应该导航到一个新页面.

你可以参考这个页面来学习如何在Flutter 中导航:https://docs.flutter.dev/cookbook/navigation/navigation-basics

ListTile(
                    title: const Text('Add User'),
                    onTap: () {
                      // Close the drawer
                      Navigator.pop(context);
                      // Navigate to new page
                      Navigator.push(
                        context,
                        MaterialPageRoute(builder: (context) => 
                        const SecondRoute()),
                       );
                    },
                  ),

Flutter相关问答推荐

在Flutter中创建具有固定行的压缩水平列表

如何使用Firebase Firestore来获取外部集合中的文档子集合中的文档

创建后检索FiRestore文档ID

使用ThemeProvider不在亮模式和暗模式之间切换

如何知道当前屏幕是否处于抖动状态?

BoxConstraints强制使用无限宽度(列中的Listview)

如何使 dart 函数变得通用?

TextField 中的富文本并获取 RenderParagraph

如何使用 Material3 创建带有高度的完美白色提升按钮?

Flutter http 请求获取 null

NotifierProvider 每次更新都会重新构建并且值不更新

Flutter:在 pubspec.yaml 中找不到assets资源

如何从flutter连接PostgreSQL数据库?

断言失败:std::move(hal_2_1_verifier).Run(). 初始化,LE音频客户端至少需要Bluetooth音频HAL V2.1

Flutter url_launcher 插件抛出java.lang.IllegalArgumentException:接收器未注册:io.flutter.plugins.urllauncher.WebViewActivity

在提供程序包更改通知程序中构建倒计时时钟

扩展磁贴尾随图标在与一个磁贴交互时更新列表中的所有内容.如何只更改展开图块的图标?

如何在屏幕按钮中排列 row() (我想在按钮中放置屏幕导航图标)

如何将图像网络装箱到具有边界半径的容器中

如何在 ElevatedButton 上设置背景 colored颜色 动画?