onWillPop - Future<bool>Function(BuildContext) can not be assigned to parameter type Future<bool>Function()

ぃ、小莉子 提交于 2021-01-07 03:01:50

问题


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(),
        ),
        ));
      }
    }
  1. How can I correct this error ?
  2. 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!