前提・我要实现的目标
我打算在按下Android后退按钮时使用WillPopScope禁用它。
问题・错误信息
将脚手架放在WillPopScope中并按Android后退按钮不会执行WillPopScope中设置的功能。
对应的源代码
Future<bool> onWillPopScope() async {
print('on');
return false;
}
Widget build(BuildContext context) {
return ChangeNotifierProvider<xxxModel>(
create:(_) => xxxModel(),
child: Stack(
children<Widget>[
WillPopScope(
onWillPop: onWillPopScope,
child: Scaffold(
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
)
),
Consumer<xxxModel>(
~~~~~~~~~~~~~~~~~~~~
),
],
),
);
}
我尝试了什么我更改了WillPopScope的位置,但是不起作用。
补充信息(固件/工具版本等)
・ flutter 1.17.5
・ Dart 2.8.4
最佳答案
如果您使用的是导航应用栏,请尝试以下过程
Future<bool> _onBackPressed() {
return showDialog(
context: context,
builder: (context) => new AlertDialog(
title: new Text('Are you sure?'),
content: new Text('Do you want to exit an App'),
actions: <Widget>[
new GestureDetector(
onTap: () => Navigator.of(context).pop(false),
child: Text("NO"),
),
SizedBox(height: 16),
new GestureDetector(
onTap: () {
exit(0);
},
child: Text("YES"),
),
],
),
) ??
false;
}
Widget build(BuildContext context) {
return Scaffold(
key: _globalKey,
body: WillPopScope(
child: _getBody(_currentIndex),//your widget list index wise
onWillPop: () async {
if (_globalKey.currentState.isDrawerOpen) {
Navigator.pop(context); // closes the drawer if opened
return Future.value(false); // won't exit the app
} else {
//only back to o index
if (_currentIndex == 0) _onBackPressed();
//return true;
setState(() {
_currentIndex = 0;
});
return false;
_onBackPressed();
// return Future.value(true); // exits the app
}
},
),
);
}