Home > database >  The argument type 'Future<void> Function()' can't be assigned to the parameter
The argument type 'Future<void> Function()' can't be assigned to the parameter

Time:12-30

Two days ago I tried to find a solution to this problem, but I did not find anything

....

  Future<void> onBackPressed() {
    return SystemNavigator.pop();
  }



  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: onBackPressed, // here i get the error
      child: Scaffold(
        floatingActionButton: FloatingActionButton(
........
.....

iget the error: The argument type 'Future< void > Function()' can't be assigned to the parameter type 'Future< bool > Function()?'.

when i change to Future < bool > Iget the error: A value of type 'Future< void >' can't be returned from the method 'onBackPressed' because it has a return type of 'Future< bool >'. Any Solution?

CodePudding user response:

The onWillPop configuration of WillPopScope requires a function with return type Future<bool>, and depending on the return value the pop will be either executed or not, see here:

If the callback returns a Future that resolves to false, the enclosing route will not be popped.

Since SystemNavigator.pop() has a return type of Future<void>, you can't return this from your onBackPressed function.

You can do this, but I think it will cause a double pop:

Future<bool> onBackPressed() async {
  await SystemNavigator.pop();
  return Future.value(true);
}

You should use the onWillPop method to decide whether the pop which was initiated by the user or your code should be executed or not. A typical example is if you want't to disable pressing back button at the home route which on Android would result in quitting your app.

CodePudding user response:

Probably not the best way, you could try the following

Future<true> onBackPressed() {
    systemNavigator.pop();
    return true
  }

But I would check why a bool is requested and then provide the logic to return true or false

CodePudding user response:

If you just want to pop the view, then let WillPopScope do the job. The following might just work fine:

@override
      Widget build(BuildContext context) {
        return WillPopScope(
          onWillPop: () async => Future.value(true),
          child: Scaffold(
            floatingActionButton: FloatingActionButton(
  • Related