我有一个onBackPressed()函数,显示AlertDialog并返回一个Future取决于用户的选择,按下退出或取消按钮。下面是代码:
// BACK PRESSED BUTTON HANDLER (FUNCTION)
Future<bool> onBackPressed() {
return showDialog(
context: context,
builder: (context) => AlertDialog(
actionsPadding: EdgeInsets.only(right: 18, bottom: 10),
// title: Text('Are you sure?'),
content: Text('Do you want to exit the application?'),
actions: <Widget>[
GestureDetector(
onTap: () => Navigator.of(context).pop(false),
child: Text("CANCEL"),
),
SizedBox(width: 20),
SizedBox(height: 16),
GestureDetector(
onTap: () => Navigator.of(context).pop(true),
child: Text("EXIT"),
),
],
),
) ??
false;
}
我需要在多个屏幕中使用这个函数,在WillPopScope小部件的帮助下处理onBackPressed事件,像这样:
return WillPopScope(
onWillPop: onBackPressed,
child: Scaffold(
appBar: AppBar( ...etc.
我试图在一个单独的文件中提取函数,但我得到一个缺少上下文的问题,需要showDialog。
我该如何处理?我觉得我错过了一些相当基本的概念,但无论如何,我会感激任何人在正确的方向上帮助我。
将上下文传递给函数
Future<bool> _onBackPressed(BuildContext context) {
...
}
并用作
//inside build(context) => Widget;
return WillPopScope(
onWillPop: () => _onBackPressed(context),// context must be visible here
child: ...
您错过了接受上下文参数,因此您的showDialog()不知道在哪里绘制。
像这样做:
Future<bool> _onBackPressed(BuildContext context) {
return showDialog(
context: context,
builder: (context) => AlertDialog(
actionsPadding: EdgeInsets.only(right: 18, bottom: 10),
// title: Text('Are you sure?'),
content: Text('Do you want to exit the application?'),
actions: <Widget>[
GestureDetector(
onTap: () => Navigator.of(context).pop(false),
child: Text("CANCEL"),
),
SizedBox(width: 20),
SizedBox(height: 16),
GestureDetector(
onTap: () => Navigator.of(context).pop(true),
child: Text("EXIT"),
),
],
),
) ??
false;
}
每次调用时,传递小部件的上下文。
_onBackPressed(上下文)