DEV Community

rrtutors
rrtutors

Posted on • Originally published at rrtutors.com

How to Handle Webview Back Button Event in Flutter?

how to handle back button event when we load web pages inside flutter webview. We know that webview will render the webpages inside native mobile applications. In flutter to load web pages we will use webview_flutter plugin. When we load webpages and while tap on internal links, it will load we pages on the same view, on this current page if we press device back button we required to load previous web page but it will close the current screen. to overcome this issue we will WillPopScope() widget to handle device back button events.

For this back button events we will show alert dialog when user press back button if there is no other previous web pages to navigate inside webview

Handle Webview Back button event

class Webpage extends StatelessWidget{
  late WebViewController _controll;

  GlobalKey_globalKey=GlobalKey();
  @override
  Widget build(BuildContext context) {

    return WillPopScope(
      onWillPop: _onBack,
      child: Scaffold(
        key: _globalKey,
        appBar: AppBar(title: Text( 'Webview Back Button '),),
        body: WebView(
          initialUrl: 'https://flutter.dev/',
          javascriptMode: JavascriptMode.unrestricted,
          onWebViewCreated: ( webViewController) {
            _controll=webViewController;


          },
          onProgress: (int progress) {

            print("WebView is loading (progress : $progress%)");
          },
          javascriptChannels: {
            _toasterJavascriptChannel(context),
          },
          navigationDelegate: (NavigationRequest request) {
            print('allowing navigation to $request');
            return NavigationDecision.navigate;
          },
          onPageStarted: (String url) {
            print('Page started loading: $url');
          },
          onPageFinished: (String url) {
            print('Page finished loading: $url');
          },
          gestureNavigationEnabled: true,
        ),
      ),
    );


  }
  JavascriptChannel _toasterJavascriptChannel(BuildContext context) {
    return JavascriptChannel(
        name: 'Toaster',
        onMessageReceived: (JavascriptMessage message) {
          // ignore: deprecated_member_use
          Scaffold.of(context).showSnackBar(
            SnackBar(content: Text(message.message)),
          );
        });
  }
}
Enter fullscreen mode Exit fullscreen mode

To check is there a possible to load previous pages inside webview by

  var value = await _controll.canGoBack(); 
Enter fullscreen mode Exit fullscreen mode

To make event changes on the fly by using the Provider NotifyChangeProvider

Download code for Handle Webview back Button events

Discussion (0)