问题
Please help me in solving this error in my flutter application:
class MyApp extends StatelessWidget {
Future<bool> _onBackPressed(BuildContext context) {
return showDialog(
context:context,builder:(BuildContext context)=>AlertDialog(title: Text('Exit'),
actions: <Widget>[
FlatButton( child:Text('NO'),onPressed: ()=>Navigator.pop(context,false)),
FlatButton( child:Text('Yes'),onPressed: ()=>Navigator.pop(context,true))
],));
}
@override
Widget build(BuildContext context) {
return WillPopScope(onWillPop:_onBackPressed, // **the argument type Future<bool>Function(BuildContext) can not be assigned to parameter Future<bool>Function()**
child: MaterialApp(
debugShowCheckedModeBanner: false,
title: 'ListViews',
theme: ThemeData(
primarySwatch: Colors.teal,
),
home: Scaffold(
appBar: AppBar(title: Text('ListViews')),
body: BodyLayout(),
),
));
}
}
- How can I correct this error ?
- After writing
Future<bool>_onBackPressed(BuildContext context) async{this error appears in the error box
Error:
the argument type Future<bool>Function(BuildContext) can not be assigned to parameter Future<bool>Function()
Please mention if you know any better way to add ON DOUBLE PRESS EXIT FLUTTER APP
回答1:
Well, the onWillPop parameter expects a Future<bool> Function(), but you provided a function that needs the BuildContext as an argument (and is thus of type Future<bool> Function(BuildContext context)).
The correct way is to wrap your function in another function:
WillPopScope(
onWillPop: () => _onBackPressed(context),
child: ...
)
And I don't think there's a more elegant way to detect double pressing back than saving the timestamp of the last back press and comparing that to the current time when back is pressed.
来源:https://stackoverflow.com/questions/58100060/onwillpop-futureboolfunctionbuildcontext-can-not-be-assigned-to-parameter