Is it possible to customize Flutter Webview error message?

Viewed 3442

I'm developing WebView mobile application in Flutter and I would like to customize webview errors, because if customer will have his wifi turned off and he got "net::ERR_ADDRESS_UNREACHABLE", it's not so good. So i would like to change this page to some custom design and show something like "This application requires internet connection, you should turn your wifi on"..

Is something like this possible? I was searching in docs and found nothing.

Thanks a lot.

1 Answers

Not sure if we can modify the actual message shown from the webview itself, but there is a workaround that I have used.

You can use a Stack widget and show a custom message in a separate widget whenever the error occurs. A sample code is below.

     Stack(
          children: [
            if (!controller.isError)
              WebView(
                javascriptMode: JavascriptMode.unrestricted,
                initialUrl: "https://some-random-url.com",
                onPageFinished: controller.onLoaded,
                onWebResourceError: controller.onError,
              ),
            if (controller.isLoading)
              Center(
                child: CircularProgressIndicator(
                  valueColor: AlwaysStoppedAnimation<Color>(Colors.black),
                ),
              ),
            if (controller.isError)
              Center(
                child: Padding(
                  padding: const EdgeInsets.only(left: 8.0, right: 8.0),
                  child: Text(
                    text: "Something went wrong, please try again", 
                  ),
                ),
              )
          ],
        ),

The Controller object you see is a GetX controller which I use for state management, you are free to use whatever you like. The main action elements are

  1. isError -> State variable which monitors if an error has occurred.

  2. WebView.onWebResourceError -> Callback function called when a certain error occurs. You can pass a function to this and this callback is only called when an error occurs. With this, you can then modify the state variable isError to be true, which will, in turn, hide the webview and show an error message at the center of the screen.

With this, you will have the error handling you are looking for.

PS: I know I am late for this answer, but I hope somebody else finds it useful.

Related