还是不能切换 class TarbarPage extends StatefulWidget { final int index; final int flag; const TarbarPage({Key? key, required this.index, required this.flag}) : super(key: key); @override State<StatefulWidget> createState() => _TarbarPageState(newIndex: index, newFlag: flag); } @override class _TarbarPageState extends State { int newIndex; int newFlag; _TarbarPageState({required this.newIndex, this.newFlag = 0}); int _currentIndex = 0; //底部导航栏当前索引 @override Widget build(BuildContext context) { print('newItem$newIndex'); print('newItem$newFlag'); final _tabPages = [ const HomePage(), StudyPage( index: newIndex, ), const FantasticStoryPage(), const SetUpPage() ]; if (newFlag != 0) { setState(() { _currentIndex = newFlag; }); } print('____$_currentIndex'); return Scaffold( body: _tabPages[_currentIndex], bottomNavigationBar: BottomNavigationBar( currentIndex: _currentIndex, onTap: (flag) { print('idnex$flag'); setState(() { _currentIndex = flag; }); String? currentPageRoute = ModalRoute.of(context)?.settings.name; print('Third page route: $currentPageRoute'); }, type: BottomNavigationBarType.fixed, items: const [ BottomNavigationBarItem( icon: Icon(Icons.home), label: ('首页'), ), BottomNavigationBarItem( icon: Icon(Icons.school), label: ('学习'), ), BottomNavigationBarItem( icon: Icon(Icons.local_library), label: ('奇闻'), ), BottomNavigationBarItem( icon: Icon(Icons.settings), label: ('设置'), ), ]), ); } }
时间: 2024-02-14 08:34:04 浏览: 129
根据你提供的代码,我发现了一个问题。在 `_TarbarPageState` 的构造函数中,`newIndex` 和 `newFlag` 被声明为实例变量,但它们没有被正确地传递给父类的构造函数。
你需要将父类的构造函数调用修改为如下形式:
```dart
_TarbarPageState({required this.newIndex, required this.newFlag}) : super();
```
这样,父类的构造函数将会被正确地调用,并且 `newIndex` 和 `newFlag` 的值将会传递给父类。
同时,在 `_TarbarPageState` 的 `build` 方法中,你可以移除 `if (newFlag != 0)` 的判断条件,直接在 `setState` 中更新 `_currentIndex` 的值。这样,无论 `newFlag` 的值是什么,都会正确地更新底部导航栏的索引。
修改后的代码如下所示:
```dart
class _TarbarPageState extends State<TarbarPage> {
int newIndex;
int newFlag;
_TarbarPageState({required this.newIndex, required this.newFlag}) : super();
int _currentIndex = 0; //底部导航栏当前索引
@override
Widget build(BuildContext context) {
print('newItem$newIndex');
print('newItem$newFlag');
final _tabPages = [
const HomePage(),
StudyPage(
index: newIndex,
),
const FantasticStoryPage(),
const SetUpPage()
];
setState(() {
_currentIndex = newFlag;
});
print('____$_currentIndex');
return Scaffold(
body: _tabPages[_currentIndex],
// ...底部导航栏代码...
);
}
}
```
希望这次修改能解决你的问题。如果问题仍然存在,请提供更多相关代码和信息,我将尽力帮助你解决。
阅读全文