Nour Mira
Nour Mira

Reputation: 17

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

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(

I get 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> I get 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?

Upvotes: 0

Views: 696

Answers (3)

flzzz
flzzz

Reputation: 543

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(

Upvotes: 0

Peter Koltai
Peter Koltai

Reputation: 9734

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.

Upvotes: 1

w461
w461

Reputation: 2678

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

Upvotes: 0

Related Questions