简体   繁体   中英

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 (eg 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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM