skip to Main Content

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?

3

Answers


  1. 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

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
  3. 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(
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search