flutterflutterwebviewplugin

Flutter - Handling WebView back press in PopScope's onPopInvokedWithResult method


I am using the following version of Flutter:

Flutter 3.24.4
Dart 3.5.4

I am using the PopScope for WebView. How I can implement the WebView backpress in onPopInvokedWithResult method?

I recently migrated from WillPopScope to PopScope and was using the onWillPop with the following function:

  Future<bool> goBack() async {
    if(await webViewController.canGoBack()){
      webViewController.goBack();
      return false;
    }
    return true;
  }

Solution

  • EDIT: After OP asked me to edit my answer to include extra info.

    EDIT2: SystemNavigator closes the app. So if you want to close the app, do this. For more, check the documentation.

    Inside onPopInvokedWithResult you should do:

    if (didPop) return;
    
    final shouldPop = await webViewController.canGoBack();
    
    if (shouldPop) {
       webViewController.goBack();
    }
    
    /// If your code arrives here, it means that shouldPop is false,
    /// that means you press back, there is no history in the navigation 
    /// stack, so we pop the webview screen and return to the WebView caller.
    SystemNavigator.pop();
    

    Check this from Flutter's documentation. The example is different, but the logic is similar.