flutter中的底部tarbar中怎么获取tarbar里页面的路由
时间: 2024-04-15 09:30:44 浏览: 76
在Flutter中,你可以使用Navigator类的静态方法来获取底部导航栏中页面的路由。以下是获取当前页面路由的示例代码:
```dart
import 'package:flutter/material.dart';
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _currentIndex = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Bottom Navigation Bar Example'),
),
body: Center(
child: Text('Page ${_currentIndex + 1}'),
),
bottomNavigationBar: BottomNavigationBar(
currentIndex: _currentIndex,
onTap: (index) {
setState(() {
_currentIndex = index;
});
},
items: [
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: 'Home',
),
BottomNavigationBarItem(
icon: Icon(Icons.search),
label: 'Search',
),
BottomNavigationBarItem(
icon: Icon(Icons.person),
label: 'Profile',
),
],
),
floatingActionButton: FloatingActionButton(
onPressed: () {
// 获取当前页面的路由
Navigator.of(context)
.restorablePush(_bottomNavRoutes[_currentIndex]);
},
child: Icon(Icons.add),
),
);
}
}
List<Page> _bottomNavRoutes = [
MaterialPage(child: HomeScreen()), // 首页
MaterialPage(child: SearchScreen()), // 搜索页
MaterialPage(child: ProfileScreen()), // 个人资料页
];
class HomeScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Home'),
),
body: Center(
child: Text('Home Screen'),
),
);
}
}
class SearchScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Search'),
),
body: Center(
child: Text('Search Screen'),
),
);
}
}
class ProfileScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Profile'),
),
body: Center(
child: Text('Profile Screen'),
),
);
}
}
```
在上面的示例中,我们使用_bottomNavRoutes列表来存储底部导航栏中每个页面的路由。当点击FloatingActionButton时,通过Navigator的restorablePush方法将当前页面的路由推入路由栈中。
你可以根据自己的需求修改_bottomNavRoutes列表中的页面,并在点击底部导航栏中的某个页面时获取相应页面的路由。
阅读全文