【发布时间】:2020-07-26 21:17:34
【问题描述】:
我目前正在使用 WillPopScope 来防止后退按钮,我在 youtube 上观看教程并在堆栈溢出中阅读了一些答案,路线是这样的。我有登录屏幕和主屏幕。当我在主屏幕时,当我从手机单击后退按钮 我想关闭我的应用程序,我尝试使用 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),
),
);
}
}
【问题讨论】: