我正在使用具有底部导航功能并为初始页面嵌套子页面的应用程序。问题是,当我进入嵌套页面,然后单击底部导航项时,我想重置堆栈,然后它应显示初始页面(在单击的任何项上):
我已经编写了以下代码,但我无法实现这一目标。
import 'package:flutter/material.dart';
class NavigatorPage extends StatefulWidget {
const NavigatorPage({Key key, this.child}) : super(key: key);
final Widget child;
@override
_NavigatorPageState createState() => _NavigatorPageState();
}
class _NavigatorPageState extends State<NavigatorPage> {
@override
Widget build(BuildContext context) {
return Navigator(
onGenerateRoute: (RouteSettings settings) {
return new MaterialPageRoute(
settings: settings,
builder: (BuildContext context) {
return Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
widget.child,
SizedBox(height: 16.0),
],
),
);
},
);
},
);
}
}
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
int _pageIndex = 0;
@override
Widget build(BuildContext context) {
print(_pageIndex);
return MaterialApp(
home: Scaffold(
body: SafeArea(
child: IndexedStack(
index: _pageIndex,
children: const <Widget>[
NavigatorPage(child: SampleClass()),
NavigatorPage(child: Text('Business')),
NavigatorPage(child: Text('School')),
],
),
),
bottomNavigationBar: BottomNavigationBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(icon: Icon(Icons.home), title: Text('')),
BottomNavigationBarItem(
icon: Icon(Icons.business), title: Text('')),
BottomNavigationBarItem(icon: Icon(Icons.school), title: Text('')),
],
currentIndex: _pageIndex,
onTap: (int index) {
setState(() {
_pageIndex = index;
});
},
),
),
);
}
}
class SampleClass extends StatelessWidget {
const SampleClass({Key key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
child: RaisedButton(
child: Text('push a route'),
onPressed: () {
Navigator.of(context).push(MaterialPageRoute(
builder: (BuildContext context) {
return NewSamplePageRoute();
},
));
},
),
);
}
}
class Page1 extends StatelessWidget {
const Page1({Key key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
child: Text('asdfs'),
);
}
}
/* */
class NewSamplePageRoute extends StatelessWidget {
const NewSamplePageRoute({Key key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
child: RaisedButton(
child: Text('push a route'),
onPressed: () {
Navigator.of(context).push(MaterialPageRoute(
builder: (BuildContext context) {
return Page1();
},
));
},
),
);
}
}
void main() {
runApp(HomePage());
}
以下是该问题的示例Gig图像: