还是不行,我获取不到其他页面传过来的的index和flag,我是需要将其他页面传过来的index赋值给_currentIndex 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(); lass _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: (index) { print('idnex$index'); setState(() { _currentIndex = index; }); 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 20:34:04 浏览: 97
要将其他页面传递的`index`赋值给`_currentIndex`,你可以在`_TarbarPageState`的`initState()`方法中进行赋值操作。以下是修改后的代码示例:
```dart
class _TarbarPageState extends State<TarbarPage> {
int _currentIndex = 0; //底部导航栏当前索引
final _tabPages = [
const HomePage(),
const StudyPage(
index: 0,
),
const FantasticStoryPage(),
const SetUpPage()
];
@override
void initState() {
super.initState();
_currentIndex = widget.index; // 将传递的index赋值给_currentIndex
}
@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: ('设置'),
),
],
),
);
}
}
```
在上述代码中,我们在`_TarbarPageState`的`initState()`方法中将传递的`widget.index`赋值给`_currentIndex`。这样,当`TarbarPage`被创建时,初始的`_currentIndex`将被设置为传递的`index`值。
请确保在创建`TarbarPage`页面时,传递正确的`index`参数。例如:
```dart
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => TarbarPage(
flag: 1,
index: 1, // 传递正确的index值
),
),
);
```
这样,底部导航栏中的第二个页面就会根据传递的`index`值进行初始化,并将其赋值给`_currentIndex`。
阅读全文