如何将上下文注入自定义函数?



我是飞镖和颤动的新手,并试图学习如何使用WillPopScope控制后退按钮。

我的类看起来像这样:

class PlayPage extends StatelessWidget {
Future<bool> _onBackPressed() {
return showDialog(
context: context,
builder: (context) => AlertDialog(
title: Text('Do you really want to leave?'),
actions: <Widget>[
FlatButton(
child: Text('No'),
onPressed: () => Navigator.pop(context,false),
),
FlatButton(
child: Text('Yes'),
onPressed: () => Navigator.pop(context),
),
],
)
); 
}

Widget build(BuildContext context) {
return WillPopScope(
onWillPop: _onBackPressed, 
child: Scaffold(
appBar: AppBar (
title: Text('Play') 
),
body: Container(
color: Colors.white,
)
)
);
}
}

我的问题: 如果我将自定义函数中的代码_onBackPressed并将其作为匿名函数分配给 onWillPop,它工作正常。 但是,如果我尝试通过 onWillPop 调用自定义函数,VSCode 会在我的 showDialog 构造函数中突出显示我的上下文参数,因为它无法识别它正在传入并且无法解析它。 而且我似乎无法弄清楚如何从onWillPop调用中传递它。

嗯,这是非常简单的开发人员解决方案,但我只是没有想到。 这是一个解决方案。

在 onWillPop 中,只需使用匿名函数调用我的自定义类方法,然后从那里传递上下文。

Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () {
return _onBackPressed(context);
}, 
child: Scaffold(
appBar: AppBar (
title: Text('Play') 
),
body: Container(
color: Colors.white,
)
)
);
}
}

最新更新