我正在youtube上观看教程并阅读堆栈溢出的一些答案后,目前正在使用WillPopScope来防止后退按钮,路由是这样的。我有登录屏幕和主屏幕..当我进入主屏幕时,当我我想关闭我的应用程序从手机上单击“后退”按钮,我已经尝试过使用WillPopScope,但是当我单击“后退”按钮时,它始终将我导航到登录屏幕,是否有办法让我的应用程序在我单击“后退”按钮时退出?这是我的代码这是登录屏幕
class _LoginScreenState extends State<LoginScreen> {
postData() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setInt('username', _username.text);
Navigator.push(context,
new MaterialPageRoute(
builder: (BuildContext context) =>
new BottomTab()));
}
@override
Widget build(BuildContext context) {
return Column(
children:<Widget>[
TextFormField(
controller: _username),
FlatButton(
child: Text("Login"),
onPressed: () {
postData(_username.text);}),];}
}
这是我的标签页
class _BottomTab extends State<BottomTab> {
Future<bool> _back() {
return showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
content: Text('exit?'),
actions: <Widget>[
FlatButton(
child: Text('ok'),
onPressed: () {
Navigator.of(context).pop(true);
},
),
FlatButton(
child: Text('no'),
onPressed: () {
Navigator.of(context).pop(false);
},
),
],
);
});
}
int _selectedIndex = 0;
_onTap(int index) {
setState(() => _myindex = index);
}
final List<Widget> pages = [
HomeScreen(),
ProfileScreen(),
];
final PageStorageBucket bucket = PageStorageBucket();
Widget _myNavigation(int selectedIndex) => BottomNavigationBar(
onTap: _onTap,
currentIndex: myindex,
type: BottomNavigationBarType.fixed,
items: const <MyTab>[
MyTab(icon: Icon(Icons.home), title: Text('Home')),
MyTab(icon: Icon(Icons.person), title: Text('Profile')),
],
);
@override
Widget build(BuildContext context) {
return FutureProvider<String>(
create: (context) async {
final prefs = await SharedPreferences.getInstance();
return prefs.getString("username");
},
child: Scaffold(
key: scaffoldKey,
body: WillPopScope(
onWillPop: back,
child: PageStorage(
child: pages[_selectedIndex],
bucket: bucket,
),
),
bottomNavigationBar: _bottomNavigationBar(_selectedIndex),
),
);
}
}
Login
屏幕在导航器堆栈中,因此,当您尝试从BottomTab
屏幕弹出时,将再次显示登录屏幕。代替:Navigator.of(context).pushReplacement(newRoute)
而不是Navigator.of(context).push(newRoute)
。它将用导航器堆栈中的“主页”路由替换“登录”路由,因此当您按下“后退”按钮时,“主页”屏幕下方的“导航器”堆栈中会出现提示,因此应用程序将关闭。