首页 > 解决方案 > 即使在对 4 个元素使用 setState 后,设置状态在底部导航栏项目中也不起作用

问题描述

当我在底部导航栏中使用 4 个项目时,即使 _currentIndex 像往常一样更改,也只有菜单显示为选定项目(索引 0)。现在该怎么办,是不是因为在类别屏幕中使用了构造函数?

 @override
  Widget build(BuildContext context) {
    User user = FirebaseAuth.instance.currentUser;

    int _currentIndex = 0;

    void onTabTapped(int index) {
      setState(() {
        _currentIndex = index;
      });
    }


    final List<Widget> _children = [
      CategoryScreen(email: user.email),
      TabBarOrder(),
      PayInScreen(),
      ProfileScreen(),
    ];

    return Scaffold(
      body: _children[_currentIndex],
      bottomNavigationBar: BottomNavigationBar(
        showSelectedLabels: true,
        onTap: onTabTapped,
        currentIndex: _currentIndex,
        type: BottomNavigationBarType.fixed,
        iconSize: 0,
        items: [
          BottomNavigationBarItem(icon: Icon(Icons.home), label: 'Menu'),
          BottomNavigationBarItem(icon: Icon(Icons.mail), label: 'Order'),
          BottomNavigationBarItem(
              icon: Icon(Icons.play_circle_filled), label: 'Pay-in'),
          BottomNavigationBarItem(
              icon: Icon(Icons.play_circle_filled), label: 'Profile'),
        ],
      ),
    );
 }

请帮忙

标签: flutter

解决方案


int _currentIndex = 0;

    void onTabTapped(int index) {
      setState(() {
        _currentIndex = index;
      });
    }

@override
  Widget build(BuildContext context) {
    User user = FirebaseAuth.instance.currentUser;

    

    final List<Widget> _children = [
      CategoryScreen(email: user.email),
      TabBarOrder(),
      PayInScreen(),
      ProfileScreen(),
    ];

    return Scaffold(
      body: _children.elementAt(_currentIndex),
      bottomNavigationBar: BottomNavigationBar(
        showSelectedLabels: true,
        onTap: onTabTapped,
        currentIndex: _currentIndex,
        type: BottomNavigationBarType.fixed,
        iconSize: 0,
        items: [
          BottomNavigationBarItem(icon: Icon(Icons.home), label: 'Menu'),
          BottomNavigationBarItem(icon: Icon(Icons.mail), label: 'Order'),
          BottomNavigationBarItem(
              icon: Icon(Icons.play_circle_filled), label: 'Pay-in'),
          BottomNavigationBarItem(
              icon: Icon(Icons.play_circle_filled), label: 'Profile'),
        ],
      ),
    );
 }

推荐阅读