用了上述方法还是显示不了,而且还报错了 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(); } class _TarbarPageState extends State { int _currentIndex = 0; //底部导航栏当前索引 final _tabPages = [ const HomePage(), const StudyPage( index: 0, ), const FantasticStoryPage(), const SetUpPage() ]; @override Widget build(BuildContext context) { return Scaffold( body: _tabPages[_currentIndex], bottomNavigationBar: BottomNavigationBar( currentIndex: _currentIndex, onTap: (flag) { setState(() { _currentIndex = flag; }); String? thirdPageRoute = ModalRoute.of(context)?.settings.name; print('Third page route: $thirdPageRoute'); }, 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: ('设置'), ), ]), ); } } Padding( padding: const EdgeInsets.all(8.0), child: ElevatedButton( onPressed: () { // Navigator.push( // context, // MaterialPageRoute( // builder: (context) => const StudyPage( // index: 0)), // 传递参数selectedIndex为1 // ); Navigator.push( context, MaterialPageRoute( builder: (context) => const TarbarPage( flag: 1, index: 0)), // 传递参数selectedIndex为1 ); }, child: const Text('狠心退出')), ),
时间: 2024-02-14 12:34:04 浏览: 129
在你的代码中,我注意到你在`_TarbarPageState`类中使用了`_currentIndex`来跟踪底部导航栏的当前索引,但是在`onTap`回调中,你使用的是`flag`作为新的索引值,这可能导致路由获取失败。
为了解决这个问题,你可以直接使用`_currentIndex`作为索引值来获取当前页面的路由信息。以下是修改后的代码示例:
```dart
class _TarbarPageState extends State<TarbarPage> {
int _currentIndex = 0; //底部导航栏当前索引
final _tabPages = [
const HomePage(),
const StudyPage(
index: 0,
),
const FantasticStoryPage(),
const SetUpPage()
];
@override
Widget build(BuildContext context) {
return Scaffold(
body: _tabPages[_currentIndex],
bottomNavigationBar: BottomNavigationBar(
currentIndex: _currentIndex,
onTap: (index) {
setState(() {
_currentIndex = index;
});
String? currentPageRoute = ModalRoute.of(context)?.settings.name;
print('Current 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: ('设置'),
),
],
),
);
}
}
```
在上述代码中,我将`onTap`回调中的参数名从`flag`改为`index`,并修改了获取当前页面路由信息的部分。现在,你应该可以正确打印出当前页面的路由信息了。请确保导航栏的索引值与 `_tabPages` 中页面的对应关系正确。
阅读全文