Search code examples
flutterwebviewback-button

How to combine together WebViewWidget and WillPopScope


How can I use WillPopScope with WebViewWidget in Flutter? I only found examples with WebView. With WillPopScope I would need that, when the back button is pressed, it returns to the page https://www.example.com, i.e. the home page of the webview.

This is my code at the moment:

import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';

void main() => runApp(MaterialApp(home: WebViewExample()));

class WebViewExample extends StatefulWidget {
  @override
  _WebViewExampleState createState() => _WebViewExampleState();
}

class _WebViewExampleState extends State<WebViewExample> {
  bool showErrorPage = false;

  WebViewController controller = WebViewController();

  @override
  void initState() {
    super.initState();

    controller.setNavigationDelegate(NavigationDelegate(
      onWebResourceError: (WebResourceError error) {
        setState(() {
          showErrorPage = true;
        });
      },
    ));

    controller.setJavaScriptMode(JavaScriptMode.unrestricted);

    controller.loadRequest(Uri.parse("https://www.example.com"));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: showErrorPage 
      ? const Center(
        child: Text('Error!'),
        style: TextStyle(fontSize: 16.0, fontWeight: FontWeight.bold)),
      )
      : WebViewWidget (
        controller: controller,
      )
    );
  }
}

Solution

  • Try this way

      @override
      Widget build(BuildContext context) {
        controller
          ..setJavaScriptMode(JavaScriptMode.unrestricted)
          ..loadRequest(Uri.parse('https://www.example.com/'));
        return Scaffold(
          body: showErrorPage 
          ? const Center(
            child: Text('Error!'),
            style: TextStyle(fontSize: 16.0, fontWeight: FontWeight.bold)),
          )
          : WillPopScope(
            onWillPop: () => _goBack(context),
            child: WebViewWidget(
              controller: controller,
            ),
          ),
        );
      }
    
      Future<bool> _goBack(BuildContext context) async {
         controller.loadRequest(Uri.parse('https://www.example.com/'));
         return Future.value(false);
      }