无状态小部件内的 Flutter 导航栏

问题描述 投票:0回答:1

我正在尝试在屏幕上实现bottomNavigationBar,它最初扩展了无状态小部件。 因此我显然无法使用

     onDestinationSelected: (index) => setState(() => this.index = index),

因为“没有为类型‘LevelSelectionScreen’定义方法‘setState’”,因为它是无状态的。

我以这种方式在无状态之前声明了我的有状态类:

    class MainPage extends StatefulWidget {
    @override
    _MainPageState createState() => _MainPageState();
    }

    class _MainPageState extends State<MainPage> {
    int index = 0;
    final pages = [
    MainMenuScreen(),
    AvailabilityScreen(),
    SettingsScreen(),
    ];
    } 

但在这种情况下缺少“State.build”的具体实现。

您能否帮我指出有状态和无状态小部件的正确顺序,因为我只能找到具有有状态类实现的导航栏。

谢谢!

这是整个导航栏的代码

    class LevelSelectionScreen extends StatelessWidget {
    const LevelSelectionScreen({super.key});
    static const _gap = SizedBox(height: 30);


    @override
    Widget build(BuildContext context) {
    final playerProgress = context.watch<PlayerProgress>();
    final onTap;
    bool isButtonPressed = false;
    int index = 0;
    return Scaffold(
    bottomNavigationBar: NavigationBar(
      height: 60,
      selectedIndex: index,
      onDestinationSelected: (index) => setState(() => this.index = 
      index),
      destinations: [
      NavigationDestination(
        icon: Icon(Icons.home),
        selectedIcon: Icon(Icons.home),
        label: 'home',

      ),
      NavigationDestination(
        icon: Icon(Icons.book),
        selectedIcon: Icon(Icons.book),
        label: 'learn',
      ),
      NavigationDestination(
        icon: Icon(Icons.gamepad),
        selectedIcon: Icon(Icons.gamepad),
        label: 'play',
      ),
       NavigationDestination(
        icon: Icon(Icons.person),
        selectedIcon: Icon(Icons.person),
        label: 'profile',
      ),
      ]),
flutter navigation uinavigationbar
1个回答
0
投票

我通过将无状态小部件转换为有状态小部件解决了这个问题

   class LevelSelectionScreen extends StatefulWidget {
   const LevelSelectionScreen({super.key});
   @override
   _LevelSelectionScreenState createState() => 
   _LevelSelectionScreenState();

   }
   class _LevelSelectionScreenState extends 
   State<LevelSelectionScreen> {
   int index = 0;
   void _onDestinationSelected(int index) {
   setState(() {
   this.index = index;
   });
   }
© www.soinside.com 2019 - 2024. All rights reserved.