androidflutterwebviewandroid-webviewflutter-inappwebview

Return to previous page when user clicks 'back' button Android InAppWebView Flutter


I'm using the InAppWebView (https://inappwebview.dev/) package in my Flutter app.

When the user clicks on the back button, it's closing the app.

I wanna make it go to the previous page of the webview.

The closest I got was this link... https://inappwebview.dev/blog/inappwebview-the-real-power-of-webviews-in-flutter/#inappwebview-simple-example

... where it shows the _webViewController.goBack() method.

The point now seems to be knowing how to intercept the Android 'back' button and call such method above.

Thank you!

P.S.: in iOS it works fine with the swipe gesture for navigating back.


Solution

  • You can wrap the scaffold with a WillPopScope class and check if there is any webview history when the user press back. If there is history use _webViewController.goBack() else pop the scope.

    WillPopScope(
          onWillPop: () async {
            if(await _webViewController.canGoBack()){
                _webViewController.goBack();
                return false;
            }
            return true;
          },
          child: Scaffold(),
    )