Community WebView Plugin - Allows Flutter to communicate with a native WebView.

Last update: May 19, 2022

Flutter Community: flutter_webview_plugin

NOTICE

We are working closely with the Flutter Team to integrate all the Community Plugin features in the Official WebView Plugin. We will try our best to resolve PRs and Bugfixes, but our priority right now is to merge our two code-bases. Once the merge is complete we will deprecate the Community Plugin in favor of the Official one.

Thank you for all your support, hopefully you'll also show it for Official Plugin too.

Keep Fluttering!

Flutter WebView Plugin

pub package

Plugin that allows Flutter to communicate with a native WebView.

Warning: The webview is not integrated in the widget tree, it is a native view on top of the flutter view. You won't be able see snackbars, dialogs, or other flutter widgets that would overlap with the region of the screen taken up by the webview.

The getSafeAcceptedType() function is available only for minimum SDK of 21. eval() function only supports SDK of 19 or greater for evaluating Javascript.

Getting Started

For help getting started with Flutter, view our online documentation.

iOS

In order for plugin to work correctly, you need to add new key to ios/Runner/Info.plist

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
    <key>NSAllowsArbitraryLoadsInWebContent</key>
    <true/>
</dict>

NSAllowsArbitraryLoadsInWebContent is for iOS 10+ and NSAllowsArbitraryLoads for iOS 9.

How it works

Launch WebView Fullscreen with Flutter navigation

new MaterialApp(
      routes: {
        "/": (_) => new WebviewScaffold(
          url: "https://www.google.com",
          appBar: new AppBar(
            title: new Text("Widget webview"),
          ),
        ),
      },
    );

Optional parameters hidden and initialChild are available so that you can show something else while waiting for the page to load. If you set hidden to true it will show a default CircularProgressIndicator. If you additionally specify a Widget for initialChild you can have it display whatever you like till page-load.

e.g. The following will show a read screen with the text 'waiting.....'.

return new MaterialApp(
  title: 'Flutter WebView Demo',
  theme: new ThemeData(
    primarySwatch: Colors.blue,
  ),
  routes: {
    '/': (_) => const MyHomePage(title: 'Flutter WebView Demo'),
    '/widget': (_) => new WebviewScaffold(
      url: selectedUrl,
      appBar: new AppBar(
        title: const Text('Widget webview'),
      ),
      withZoom: true,
      withLocalStorage: true,
      hidden: true,
      initialChild: Container(
        color: Colors.redAccent,
        child: const Center(
          child: Text('Waiting.....'),
        ),
      ),
    ),
  },
);

FlutterWebviewPlugin provide a singleton instance linked to one unique webview, so you can take control of the webview from anywhere in the app

listen for events

final flutterWebviewPlugin = new FlutterWebviewPlugin();

flutterWebviewPlugin.onUrlChanged.listen((String url) {

});

Listen for scroll event in webview

final flutterWebviewPlugin = new FlutterWebviewPlugin();
flutterWebviewPlugin.onScrollYChanged.listen((double offsetY) { // latest offset value in vertical scroll
  // compare vertical scroll changes here with old value
});

flutterWebviewPlugin.onScrollXChanged.listen((double offsetX) { // latest offset value in horizontal scroll
  // compare horizontal scroll changes here with old value
});

Note: Do note there is a slight difference is scroll distance between ios and android. Android scroll value difference tends to be larger than ios devices.

Hidden WebView

final flutterWebviewPlugin = new FlutterWebviewPlugin();

flutterWebviewPlugin.launch(url, hidden: true);

Close launched WebView

flutterWebviewPlugin.close();

Webview inside custom Rectangle

final flutterWebviewPlugin = new FlutterWebviewPlugin();

flutterWebviewPlugin.launch(url,
  fullScreen: false,
  rect: new Rect.fromLTWH(
    0.0,
    0.0,
    MediaQuery.of(context).size.width,
    300.0,
  ),
);

Injecting custom code into the webview

Use flutterWebviewPlugin.evalJavaScript(String code). This function must be run after the page has finished loading (i.e. listen to onStateChanged for events where state is finishLoad).

If you have a large amount of JavaScript to embed, use an asset file. Add the asset file to pubspec.yaml, then call the function like:

Future<String> loadJS(String name) async {
  var givenJS = rootBundle.loadString('assets/$name.js');
  return givenJS.then((String js) {
    flutterWebViewPlugin.onStateChanged.listen((viewState) async {
      if (viewState.type == WebViewState.finishLoad) {
        flutterWebViewPlugin.evalJavascript(js);
      }
    });
  });
}

Accessing local files in the file system

Set the withLocalUrl option to true in the launch function or in the Webview scaffold to enable support for local URLs.

Note that, on iOS, the localUrlScope option also needs to be set to a path to a directory. All files inside this folder (or subfolder) will be allowed access. If ommited, only the local file being opened will have access allowed, resulting in no subresources being loaded. This option is ignored on Android.

Ignoring SSL Errors

Set the ignoreSSLErrors option to true to display content from servers with certificates usually not trusted by the Webview like self-signed certificates.

Warning: Don't use this in production.

Note that on iOS, you need to add new key to ios/Runner/Info.plist

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
    <key>NSAllowsArbitraryLoadsInWebContent</key>
    <true/>
</dict>

NSAllowsArbitraryLoadsInWebContent is for iOS 10+ and NSAllowsArbitraryLoads for iOS 9. Otherwise you'll still not be able to display content from pages with untrusted certificates.

You can test your ignorance if ssl certificates is working e.g. through https://self-signed.badssl.com/

Webview Events

  • Stream<Null> onDestroy
  • Stream<String> onUrlChanged
  • Stream<WebViewStateChanged> onStateChanged
  • Stream<double> onScrollXChanged
  • Stream<double> onScrollYChanged
  • Stream<String> onError

Don't forget to dispose webview flutterWebviewPlugin.dispose()

Webview Functions

Future<Null> launch(String url, {
    Map<String, String> headers: null,
    Set<JavascriptChannel> javascriptChannels: null,
    bool withJavascript: true,
    bool clearCache: false,
    bool clearCookies: false,
    bool hidden: false,
    bool enableAppScheme: true,
    Rect rect: null,
    String userAgent: null,
    bool withZoom: false,
    bool displayZoomControls: false,
    bool withLocalStorage: true,
    bool withLocalUrl: true,
    String localUrlScope: null,
    bool withOverviewMode: false,
    bool scrollBar: true,
    bool supportMultipleWindows: false,
    bool appCacheEnabled: false,
    bool allowFileURLs: false,
    bool useWideViewPort: false,
    String invalidUrlRegex: null,
    bool geolocationEnabled: false,
    bool debuggingEnabled: false,
    bool ignoreSSLErrors: false,
});
Future<String> evalJavascript(String code);
Future<Map<String, dynamic>> getCookies();
Future<Null> cleanCookies();
Future<Null> resize(Rect rect);
Future<Null> show();
Future<Null> hide();
Future<Null> reloadUrl(String url);
Future<Null> close();
Future<Null> reload();
Future<Null> goBack();
Future<Null> goForward();
Future<Null> stopLoading();
Future<bool> canGoBack();
Future<bool> canGoForward();

GitHub

https://github.com/fluttercommunity/flutter_webview_plugin
Comments
  • 1. Can not open url in iOS

    I try to open url in Android using Flutter Webview Plugin and it works, but in iOS simulator it doesn't work. For example: I open google.com and then I search a website, I can not open the site by clicking it in google search list. Please help to resolve this..

    Reviewed by gunadharma at 2018-11-06 08:17
  • 2. Does not scroll when keyboard is appeared on focus of text field

    I do Instagram implicit authentification and show login page in webview_plagin using WebViewScaffold. Page is short, so no scroll. When focus on any text field (username and password) keyboard are appeared and I can not see input field anymore.

    Is there a way to add a scrolling?

    Reviewed by marica27 at 2018-07-19 11:30
  • 3. MissingPluginException(No implementation found for method close on channel flutter_webview_plugin)

    I am trying to have WebView in Flutter using WebviewScaffold widget.

    I have installed flutter_webview_plugin: "^0.1.0+1"

    but I am getting ERROR: MissingPluginException(No implementation found for method close on channel flutter_webview_plugin) . . . MissingPluginException(No implementation found for method launch on channel flutter_webview_plugin) . . .

    Below is how my page looks like:

    import 'package:flutter/material.dart';
    import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';
    
    
    class BulkProductUpdatePageRoute extends MaterialPageRoute {
      BulkProductUpdatePageRoute():
          super(builder: (BuildContext context) => new BulkProductUpdatePage());
    }
    
    class BulkProductUpdatePage extends StatefulWidget {
      @override
      _BulkProductUpdatePageState createState() => new _BulkProductUpdatePageState();
    }
    
    class _BulkProductUpdatePageState extends State<BulkProductUpdatePage> {
    
      @override
      Widget build(BuildContext context) {
        return new WebviewScaffold(
          appBar: new AppBar(
            leading: new RetailAppBarLeading(),
            title: new Text('Bulk Product Update'),
            bottom: appBarBottom(
              child: new Container(
                child: new TextField(
                  decoration: new InputDecoration(
                      icon: new Icon(
                        Icons.search,
                        color: Colors.grey,
                      ),
                      hideDivider: true,
                      hintText: 'Search Products'
                  ),
                ),
                padding: new EdgeInsets.only(
                    bottom: 5.0
                ),
              ),
            ),
          ),
          url: 'https://pub.dartlang.org/packages/flutter_webview_plugin#-installing-tab-',
        );
      }
    }
    
    
    Reviewed by arnoldparge at 2018-02-01 06:54
  • 4. Webview crashes on url change on iOS

    I'm getting the following error while trying to use the webview on iOS (via the Simulator) which is crashing the app. It only seems to happen for some URLs. On Android everything works fine, but on iOS I'm able to get through the login prompt and oAuth acceptance pages, but then it crashes when it tries to navigate to the actual authenticated app.

    Unsupported value: <FlutterError: 0x60800023b740> of type FlutterError
    *** First throw call stack:
    (
    	0   CoreFoundation                      0x000000010dff51e6 __exceptionPreprocess + 294
    	1   libobjc.A.dylib                     0x000000010d68a031 objc_exception_throw + 48
    	2   CoreFoundation                      0x000000010dffa472 +[NSException raise:format:arguments:] + 98
    	3   Foundation                          0x000000010d12d652 -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 193
    	4   Flutter                             0x000000010b89a808 -[FlutterStandardWriter writeValue:] + 2091
    	5   Flutter                             0x000000010b89ae52 -[FlutterStandardMethodCodec encodeMethodCall:] + 136
    	6   Flutter                             0x000000010b8945dc -[FlutterMethodChannel invokeMethod:arguments:] + 58
    	7   flutter_webview_plugin              0x000000010d052b62 -[FlutterWebviewPlugin webView:didFailNav<…>
    Lost connection to device.
    
    Reviewed by jimsimon at 2018-04-13 20:49
  • 5. Won't load on release

    For some reason when I do a simple flutterWebviewPlugin.launch for release it does not work, but a regular build (debug) does. I am sure I am missing something simple. Any ideas?

    Reviewed by bagintz at 2019-03-01 16:25
  • 6. How to clear cookies (iOS)

    The options clearCookies work perfectly on Android but not working on iOS

    webview.launch(
        "https://google.com",
        clearCache: true,
        clearCookies: true,
    );
    
    Reviewed by hungps at 2018-10-02 16:35
  • 7. Remove the appbar???

    When I launch webview in flutter, I don't need the appbar (back button and the title). How can I remove it?

    image Seem like this is the arguments for function "launch", but I can't use it as well.. Thanks you guys.

    Reviewed by jackphuongvu at 2018-01-12 10:20
  • 8. Receiving Cookies in WebView

    I was wondering, if it is possible to get data from cookies, set in the web view, to the flutter application. My use case is a custom auth mechanism which works by authentication with google on server side and sending a cookie with the client credentials in a cookie to the frontend (in this case my flutter app). Is this possible with this plugin?

    I saw both #7 and #8 and am not sure about this approach because of the cookie instead of a redirect url and query parameters.

    Reviewed by r-wittmann at 2017-08-17 16:14
  • 9. Permissions Location android

    Hello, im need the location permission on my web view, i have a button to request this permission, in the browser work fine but in the webview no work, the pop-up with permission not shows, i added location permission in AndroidManifest.xml but nothing happened, can help me with this?

    Reviewed by mgdecondux at 2019-10-01 16:30
  • 10. Add support for sending data from webview to native in iOS and Android

    • create the local http-server in example/html folder (for example: by http-server)
    • modify the messageUrl in main.dart to your http-server url
    • run the example project and click the Open Webview (message demo)button
    • click send to flutter button in webview and you can see the result in the bottom.
    Reviewed by OPY-bbt at 2019-06-26 14:17
  • 11. enable Javascript in iOS, support abort loading specific URLs

    I create this pull request to give WebView few features:

    • enable Javascript in iOS.
    • support abort loading specific URLs by using regex pattern. Native webview in Android and iOS will use this regex to determine to continue or abort loading an URL in method shouldOverrideUrlLoading in Android and webView:decidePolicyForNavigationAction:decisionHandler in iOS
    Reviewed by hnvn at 2019-01-08 16:21
  • 12. No option to change font size of html content inside webview

    System info

    Issue occurs on: iOS / Android / both Plugin version: ^0.4.0 Flutter doctor output: NA

    Steps to Reproduce

    1. use this plugin in your app
    2. there is no option found to change the font size of html content which is shown inside webiew (like we have in android as webview.getSettings().setDefaultFontSize(14)). Need similar kind of option in flutter supported by both android and ios

    Stucked in this please help.

    Reviewed by neeluagrawal04 at 2022-05-08 06:09
  • 13. Download a static file by href, on post request or XMLHttpRequest

    Use case

    We have a mobile app and at some point our users need to import some data into our mobile app but to do it users need to export this data from a 3rd party website first. So we open a webview to allow our users to still "be inside" of our app, sign in to a 3rd party website and click on an Export button there to download a file. After that users click on our Import button and imports the just downloaded file.

    Proposal

    Because of there different 3rd party websites they do provide different ways of export. So it would be really great to have all of them like:

    • Download a static file by
    • Download on post/get request
    • Download on XMLHttpRequest
    Reviewed by okarpov at 2022-04-29 11:08
  • 14. Some links not working properly in IOS 12 pro

    System info

    Issue occurs on: iOS / Android / both Plugin version: xxx Flutter doctor output:

    paste it here...
    

    Steps to Reproduce

    1. ...
    2. ...
    3. ...

    Logs

    Reviewed by Rajesh-Technovert at 2022-04-13 07:57
  • 15. Detect if Webview scroll reach the end

    I'm implementing the EULA WebView with the "Accept" button which must be visible only when the user scrolls to the bottom of the web page. The current scroll position is already implemented and it's working great:

    webviewPlugin
          ..onScrollYChanged.listen((double offsetY) {
    }
    

    Is it possible to get the max scroll value? (getMaxScrollAmount or similar...)

    Reviewed by djankey at 2022-04-03 19:53
  • 16. uses a deprecated version of the Android embedding

    The plugin flutter_webview_plugin uses a deprecated version of the Android embedding. To avoid unexpected runtime failures, or future build failures, try to see if this plugin supports the Android V2 embedding. Otherwise, consider removing it since a future release of Flutter will remove these deprecated APIs. image

    Reviewed by AhmedKhattab95 at 2022-02-24 14:37

Related

Timy - open source mobile app for groups to communicate and organize themselves. Built with flutter.
Timy - open source mobile app for groups to communicate and organize themselves. Built with flutter.

Timy app An amazing open-source group messaging app build with flutter. ✨ Main Features Multiple groups (similar to Teams in Slack). Multiple open or

May 20, 2022
May 6, 2022
Utility Manager Flutter Application is made with Flutter and Supabase which allows user to add task, set remainder to the task, set color to separate tasks and it allows to add URL with URL's informations.
Utility Manager Flutter Application is made with Flutter and Supabase which allows user to add task, set remainder to the task, set color to separate tasks and it allows to add URL with URL's informations.

Utility Manager Flutter Application! Utility Manager Flutter Application is made with Flutter and Supabase which allows user to add task, set remainde

Jan 6, 2022
This is a Flutter project inspired by sustainability and powered by the community
This is a Flutter project inspired by sustainability and powered by the community

This is a Flutter project inspired by sustainability and powered by the community. TrashTrack is a demo of a social platform with geolocation features that brings people a new way of collaboration.

Oct 31, 2021
Pig Community Mobile Application

Hello Fellow Pigsters Pig Community Mobile Application Getting Started This project is a starting point for a Flutter application. A few resources to

May 21, 2021
Let's makeover your backyard with the power of community
Let's makeover your backyard with the power of community

Backover Let's give our backyard a makeover! ✨ 25 out of 30 people are usually pretty unhappy about how their backyard looks. Even if some people like

Jan 19, 2022
This is an official mobile app for community classroom

Community Classroom Mobile app This repository contains code for mobile app of community classroom. Architecture to be followed for each feature: We a

Apr 17, 2022
Application of Community for students

small_talk An Anonymous Community for Teenage Student Getting Started This project is a starting point for a Flutter application. A few resources to g

Dec 10, 2021
Actively maintained, community-driven chat UI implementation with an optional Firebase BaaS.
Actively maintained, community-driven chat UI implementation with an optional Firebase BaaS.

Flutter Chat UI Actively maintained, community-driven chat UI implementation with an optional Firebase BaaS. Flyer Chat is a platform for creating in-

May 18, 2022
Showwcase is a professional network built for developers to connect, build community, and find new opportunities.

Showwcase Generated by the Very Good CLI ?? Showwcase is a professional network built for developers to connect, build community, and find new opportu

Jan 13, 2022
PaperClip - A trading, community based mobile platform.
PaperClip - A trading, community based mobile platform.

PaperClip A trading, community based mobile platform. Getting Started This project is still under development and will not be released in public. The

Mar 20, 2022
Plugin with native integration for WebSocket.

NOTE: This repository is no longer maintained by ENGAPP. It was moved to be maintained by Kunlatek on the following link: https://github.com/kunlatek/

Dec 20, 2021
Flutter plugin that allows users to create TextAvatar easily!
Flutter plugin that allows users to create TextAvatar easily!

Colorize Text Avatar Colorize Text Avatar is a package to generate avatar based on your user initials. It supports to generate avatars based on your s

Jan 23, 2022
This plugin allows Flutter desktop apps to resizing and repositioning the window.

window_manager This plugin allows Flutter desktop apps to resizing and repositioning the window. window_manager Platform Support Quick Start Installat

May 19, 2022
This plugin allows Flutter desktop apps to defines system/inapp wide hotkey (i.e. shortcut).

hotkey_manager This plugin allows Flutter desktop apps to defines system/inapp wide hotkey (i.e. shortcut). hotkey_manager Platform Support Quick Star

May 13, 2022
Plant Manager is an application that was developed on Rocketseat NLW5 with React Native but was rebuilt using Flutter.
Plant Manager is an application that was developed on Rocketseat NLW5 with React Native but was rebuilt using Flutter.

Technologies | Project | Layout | License ?? Technologies This project was developed with the following technologies: Flutter ?? Project Plant Manager

Aug 11, 2021
This is the new version of my Task app "Tasko" which was done in Java. She is now in Flutter for the HotReload and the native Cross-Platform.
This is the new version of my Task app

tasko_rem The Tasko App is now compatible on iOS, Android and others distribution, because it's made with Flutter ✨ You can now add task, check them o

May 2, 2022
A new practical project made with Flutter and some native widgets, movie API, provider state and more.
A new practical project made with Flutter and some native widgets, movie API, provider state and more.

Flutter Movie App This project was created with Flutter and some native Widgets like SingleChildScrollView, Hero Animation, SliverAppBar, StreamBuilde

Nov 9, 2021
For flutter native plugins, send event to main thread.

native_main_thread A new Flutter plugin. Getting Started This project is a starting point for a Flutter plug-in package, a specialized package that in

Nov 26, 2021