Flutter中BottomNavigationBar配置后状态无变化问题求助
嘿,我一眼就瞅出问题所在啦!你把_selectedIndex这个关键的状态变量定义在了build方法里面,这可不行——每次Flutter重新构建组件的时候,build方法都会重新执行,_selectedIndex就会被重新赋值为0,所以你点导航项的时候看起来完全没反应,其实是状态刚更新就被重置回去了。
正确的做法是把_selectedIndex放到State类的成员变量位置,也就是build方法外面,这样它的状态就能在组件的整个生命周期里被保留下来。另外我注意到你还定义了一个_zzzxx方法但没实际用到,也可以顺手把它整合到逻辑里。
给你修正后的完整代码:
import 'package:flutter/material.dart'; class Thursday20 extends StatefulWidget { const Thursday20({super.key}); @override State<Thursday20> createState() => _Thursday20State(); } class _Thursday20State extends State<Thursday20> { // 把状态变量移到这里,作为State类的成员 int _selectedIndex = 0; void _zzzxx(int index) { setState(() { _selectedIndex = index; }); } @override Widget build(BuildContext context) { final screens = [ Center(child: Text('HHHHH', style: TextStyle(fontSize: 60),),), Center(child: Text('SSSSS', style: TextStyle(fontSize: 60),),), Center(child: Text('EEEEE', style: TextStyle(fontSize: 60),),), Center(child: Text('PPPPP', style: TextStyle(fontSize: 60),),), ]; return Scaffold( body: screens[_selectedIndex], bottomNavigationBar: BottomNavigationBar( backgroundColor: Colors.blueGrey[700], selectedItemColor: Colors.blueGrey[100], unselectedItemColor: Colors.blueGrey, currentIndex: _selectedIndex, // 这里可以直接用你定义的_zzzxx方法,或者继续用匿名函数都可以 onTap: _zzzxx, iconSize: 37.0, selectedFontSize: 16.0, unselectedFontSize: 11.0, items: [ BottomNavigationBarItem( icon: Icon(Icons.label_important), label: 'Forwards', backgroundColor: Colors.blueGrey[700], ), BottomNavigationBarItem( icon: Icon(Icons.wallet), label: 'Wallet', backgroundColor: Colors.blueGrey[700], ), BottomNavigationBarItem( icon: Icon(Icons.backspace_outlined), label: 'Delete', backgroundColor: Colors.blueGrey[700], ), BottomNavigationBarItem( icon: Icon(Icons.zoom_out_map_outlined), label: 'Zoom Out', backgroundColor: Colors.blueGrey[700], ), ], ), ); } }
这样修改之后,你再点击底部导航项,对应的页面内容就会跟着切换啦~
备注:内容来源于stack exchange,提问作者mathems32
相关产品推荐
相关产品推荐

