wepowf
wepowf

Reputation: 53

How to add back button to WebView in Flutter to dismiss the WebView altogether?

Currently when I tap on an image, it should open a web view as the image object has an associated url. I am using the url_launcher library for Flutter, and I have implemented the code as follows:

        onTap: () async {
          final url = image.url;
          if (await canLaunch(url)) {
            await launch(
              url,
              forceSafariVC: true,
              forceWebView: true,
              enableJavaScript: true,
            );
          }
        },

My understanding is that this launches a WebView, which is an in-app browser rather than taking the user out of the app and into a separate browser app. This works fine, but the page loads much slower and Javascript elements do not work properly (e.g. animated text on websites). On the other hand,

        onTap: () async {
          final url = banners[index].url;
          if (await canLaunch(url)) {
            await launch(
              url
            );
          }
        },

works much better as it is faster and everything loads in properly, but it opens an external browser, which is not what I want.

Another issue is that I would like to add a Done button on the top left corner of the WebView to completely exit the WebView and return to where I was in the app. I only have a back button on the bottom left (on the Android emulator), that lets me go to the previous page I was at in the browser. How do I customise the layout of the WebView, if I do not have any access to it? The url_launcher seems to handle the WebView creation internally, so I'm wondering how can I gain access from the above code to add that button?

Thank you!

Upvotes: 3

Views: 1705

Answers (1)

Shatanik Mahanty
Shatanik Mahanty

Reputation: 362

If you use the native webview in this manner then you can't customise the ui. But instead, since you are displaying image you can use image.network from flutter.

    Image.network(imgURL,fit: BoxFit.fill,
      loadingBuilder:(BuildContext context, Widget child,ImageChunkEvent loadingProgress) {
      if (loadingProgress == null) 
        return child;
      return Center(
         child: CircularProgressIndicator(
         value: loadingProgress.expectedTotalBytes != null ? 
                loadingProgress.cumulativeBytesLoaded / loadingProgress.expectedTotalBytes
                 : null,
      ),
     );
    },
   ),

Or, you can also use official webview plugin from flutter team to create in app web view.

webview_flutter: ^2.3.1

In this approaches if you add a back button in ui you can the use Navigator.pop(context); on onPressed property in button to go back

Upvotes: 1

Related Questions