Explorar el Código

fix play video error

hwh97 hace 6 años
commit
05a94beedf
Se han modificado 96 ficheros con 7453 adiciones y 0 borrados
  1. 303 0
      CHANGELOG.md
  2. 27 0
      LICENSE
  3. 36 0
      README.md
  4. 29 0
      android/android-webview_flutter.iml
  5. 39 0
      android/build.gradle
  6. 1 0
      android/settings.gradle
  7. 2 0
      android/src/main/AndroidManifest.xml
  8. 143 0
      android/src/main/java/io/flutter/plugins/webviewflutter/DisplayListenerProxy.java
  9. 56 0
      android/src/main/java/io/flutter/plugins/webviewflutter/FlutterCookieManager.java
  10. 325 0
      android/src/main/java/io/flutter/plugins/webviewflutter/FlutterWebView.java
  11. 204 0
      android/src/main/java/io/flutter/plugins/webviewflutter/FlutterWebViewClient.java
  12. 189 0
      android/src/main/java/io/flutter/plugins/webviewflutter/InputAwareWebView.java
  13. 58 0
      android/src/main/java/io/flutter/plugins/webviewflutter/JavaScriptChannel.java
  14. 112 0
      android/src/main/java/io/flutter/plugins/webviewflutter/ThreadedInputConnectionProxyAdapterView.java
  15. 31 0
      android/src/main/java/io/flutter/plugins/webviewflutter/WebViewFactory.java
  16. 74 0
      android/src/main/java/io/flutter/plugins/webviewflutter/WebViewFlutterPlugin.java
  17. 8 0
      example/.metadata
  18. 8 0
      example/README.md
  19. 62 0
      example/android/app/build.gradle
  20. 5 0
      example/android/app/gradle/wrapper/gradle-wrapper.properties
  21. 13 0
      example/android/app/src/androidTestDebug/java/io/flutter/plugins/webviewflutterexample/EmbeddingV1ActivityTest.java
  22. 13 0
      example/android/app/src/androidTestDebug/java/io/flutter/plugins/webviewflutterexample/MainActivityTest.java
  23. 51 0
      example/android/app/src/main/AndroidManifest.xml
  24. 20 0
      example/android/app/src/main/java/io/flutter/plugins/webviewflutterexample/EmbeddingV1Activity.java
  25. 12 0
      example/android/app/src/main/res/drawable/launch_background.xml
  26. BIN
      example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png
  27. BIN
      example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png
  28. BIN
      example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png
  29. BIN
      example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
  30. BIN
      example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
  31. 8 0
      example/android/app/src/main/res/values/styles.xml
  32. 29 0
      example/android/build.gradle
  33. 4 0
      example/android/gradle.properties
  34. 6 0
      example/android/gradle/wrapper/gradle-wrapper.properties
  35. 15 0
      example/android/settings.gradle
  36. BIN
      example/assets/sample_audio.ogg
  37. 26 0
      example/ios/Flutter/AppFrameworkInfo.plist
  38. 2 0
      example/ios/Flutter/Debug.xcconfig
  39. 2 0
      example/ios/Flutter/Release.xcconfig
  40. 625 0
      example/ios/Runner.xcodeproj/project.pbxproj
  41. 7 0
      example/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata
  42. 97 0
      example/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme
  43. 10 0
      example/ios/Runner.xcworkspace/contents.xcworkspacedata
  44. 8 0
      example/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist
  45. 10 0
      example/ios/Runner/AppDelegate.h
  46. 17 0
      example/ios/Runner/AppDelegate.m
  47. 122 0
      example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json
  48. BIN
      example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png
  49. BIN
      example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png
  50. BIN
      example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png
  51. BIN
      example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png
  52. BIN
      example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png
  53. BIN
      example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png
  54. BIN
      example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png
  55. BIN
      example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png
  56. BIN
      example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png
  57. BIN
      example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png
  58. BIN
      example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png
  59. BIN
      example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png
  60. BIN
      example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png
  61. BIN
      example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png
  62. BIN
      example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png
  63. 23 0
      example/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json
  64. BIN
      example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png
  65. BIN
      example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png
  66. BIN
      example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png
  67. 5 0
      example/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md
  68. 37 0
      example/ios/Runner/Base.lproj/LaunchScreen.storyboard
  69. 26 0
      example/ios/Runner/Base.lproj/Main.storyboard
  70. 47 0
      example/ios/Runner/Info.plist
  71. 13 0
      example/ios/Runner/main.m
  72. 22 0
      example/ios/webview_flutter_exampleTests/Info.plist
  73. 338 0
      example/lib/main.dart
  74. 24 0
      example/pubspec.yaml
  75. 726 0
      example/test_driver/webview_flutter_e2e.dart
  76. 16 0
      example/test_driver/webview_flutter_e2e_test.dart
  77. 0 0
      ios/Assets/.gitkeep
  78. 14 0
      ios/Classes/FLTCookieManager.h
  79. 49 0
      ios/Classes/FLTCookieManager.m
  80. 21 0
      ios/Classes/FLTWKNavigationDelegate.h
  81. 68 0
      ios/Classes/FLTWKNavigationDelegate.m
  82. 8 0
      ios/Classes/FLTWebViewFlutterPlugin.h
  83. 18 0
      ios/Classes/FLTWebViewFlutterPlugin.m
  84. 32 0
      ios/Classes/FlutterWebView.h
  85. 415 0
      ios/Classes/FlutterWebView.m
  86. 17 0
      ios/Classes/JavaScriptChannelHandler.h
  87. 36 0
      ios/Classes/JavaScriptChannelHandler.m
  88. 89 0
      ios/Tests/FLTWebViewTests.m
  89. 26 0
      ios/webview_flutter.podspec
  90. 372 0
      lib/platform_interface.dart
  91. 63 0
      lib/src/webview_android.dart
  92. 47 0
      lib/src/webview_cupertino.dart
  93. 160 0
      lib/src/webview_method_channel.dart
  94. 693 0
      lib/webview_flutter.dart
  95. 28 0
      pubspec.yaml
  96. 1211 0
      test/webview_flutter_test.dart

+ 303 - 0
CHANGELOG.md

@@ -0,0 +1,303 @@
+## 0.3.19+9
+
+* Remove example app's iOS workspace settings.
+
+## 0.3.19+8
+
+* Make the pedantic dev_dependency explicit.
+
+## 0.3.19+7
+
+* Remove the Flutter SDK constraint upper bound.
+
+## 0.3.19+6
+
+* Enable opening links that target the "_blank" window (links open in same window).
+
+## 0.3.19+5
+
+* On iOS, always keep contentInsets of the WebView to be 0.
+* Fix XCTest case to follow XCTest naming convention.
+
+## 0.3.19+4
+
+* On iOS, fix the scroll view content inset is automatically adjusted. After the fix, the content position of the WebView is customizable by Flutter.
+* Fix an iOS 13 bug where the scroll indicator shows at random location.
+
+## 0.3.19+3
+
+* Setup XCTests.
+
+## 0.3.19+2
+
+* Migrate from deprecated BinaryMessages to ServicesBinding.instance.defaultBinaryMessenger.
+
+## 0.3.19+1
+
+* Raise min Flutter SDK requirement to the latest stable. v2 embedding apps no
+  longer need to special case their Flutter SDK requirement like they have
+  since v0.3.15+3.
+
+## 0.3.19
+
+* Add setting for iOS to allow gesture based navigation.
+
+## 0.3.18+1
+
+* Be explicit that keyboard is not ready for production in README.md.
+
+## 0.3.18
+
+* Add support for onPageStarted event.
+* Remove the deprecated `author:` field from pubspec.yaml
+* Migrate to the new pubspec platforms manifest.
+* Require Flutter SDK 1.10.0 or greater.
+
+## 0.3.17
+
+* Fix pedantic lint errors. Added missing documentation and awaited some futures
+  in tests and the example app.
+
+## 0.3.16
+
+* Add support for async NavigationDelegates. Synchronous NavigationDelegates
+  should still continue to function without any change in behavior.
+
+## 0.3.15+3
+
+* Re-land support for the v2 Android embedding. This correctly sets the minimum
+  SDK to the latest stable and avoid any compile errors. *WARNING:* the V2
+  embedding itself still requires the current Flutter master channel
+  (flutter/flutter@1d4d63a) for text input to work properly on all Android
+  versions.
+
+## 0.3.15+2
+
+* Remove AndroidX warnings.
+
+## 0.3.15+1
+
+* Revert the prior embedding support add since it requires an API that hasn't
+  rolled to stable.
+
+## 0.3.15
+
+* Add support for the v2 Android embedding. This shouldn't affect existing
+  functionality. Plugin authors who use the V2 embedding can now register the
+  plugin and expect that it correctly responds to app lifecycle changes.
+
+## 0.3.14+2
+
+* Define clang module for iOS.
+
+## 0.3.14+1
+
+* Allow underscores anywhere for Javascript Channel name.
+
+## 0.3.14
+
+* Added a getTitle getter to WebViewController.
+
+## 0.3.13
+
+* Add an optional `userAgent` property to set a custom User Agent.
+
+## 0.3.12+1
+
+* Temporarily revert getTitle (doing this as a patch bump shortly after publishing).
+
+## 0.3.12
+
+* Added a getTitle getter to WebViewController.
+
+## 0.3.11+6
+
+* Calling destroy on Android webview when flutter webview is getting disposed.
+
+## 0.3.11+5
+
+* Reduce compiler warnings regarding iOS9 compatibility by moving a single
+  method back into a `@available` block.
+
+## 0.3.11+4
+
+* Removed noisy log messages on iOS.
+
+## 0.3.11+3
+
+* Apply the display listeners workaround that was shipped in 0.3.11+1 on
+  all Android versions prior to P.
+
+## 0.3.11+2
+
+* Add fix for input connection being dropped after a screen resize on certain
+  Android devices.
+
+## 0.3.11+1
+
+* Work around a bug in old Android WebView versions that was causing a crash
+  when resizing the webview on old devices.
+
+## 0.3.11
+
+* Add an initialAutoMediaPlaybackPolicy setting for controlling how auto media
+  playback is restricted.
+
+## 0.3.10+5
+
+* Add dependency on `androidx.annotation:annotation:1.0.0`.
+
+## 0.3.10+4
+
+* Add keyboard text to README.
+
+## 0.3.10+3
+
+* Don't log an unknown setting key error for 'debuggingEnabled' on iOS.
+
+## 0.3.10+2
+
+* Fix InputConnection being lost when combined with route transitions.
+
+## 0.3.10+1
+
+* Add support for simultaenous Flutter `TextInput` and WebView text fields.
+
+## 0.3.10
+
+* Add partial WebView keyboard support for Android versions prior to N. Support
+  for UIs that also have Flutter `TextInput` fields is still pending. This basic
+  support currently only works with Flutter `master`. The keyboard will still
+  appear when it previously did not when run with older versions of Flutter. But
+  if the WebView is resized while showing the keyboard the text field will need
+  to be focused multiple times for any input to be registered.
+
+## 0.3.9+2
+
+* Update Dart code to conform to current Dart formatter.
+
+## 0.3.9+1
+
+* Add missing template type parameter to `invokeMethod` calls.
+* Bump minimum Flutter version to 1.5.0.
+* Replace invokeMethod with invokeMapMethod wherever necessary.
+
+## 0.3.9
+
+* Allow external packages to provide webview implementations for new platforms.
+
+## 0.3.8+1
+
+* Suppress deprecation warning for BinaryMessages. See: https://github.com/flutter/flutter/issues/33446
+
+## 0.3.8
+
+* Add `debuggingEnabled` property.
+
+## 0.3.7+1
+
+* Fix an issue where JavaScriptChannel messages weren't sent from the platform thread on Android.
+
+## 0.3.7
+
+* Fix loadUrlWithHeaders flaky test.
+
+## 0.3.6+1
+
+* Remove un-used method params in webview\_flutter
+
+## 0.3.6
+
+* Add an optional `headers` field to the controller.
+
+## 0.3.5+5
+
+* Fixed error in documentation of `javascriptChannels`.
+
+## 0.3.5+4
+
+* Fix bugs in the example app by updating it to use a `StatefulWidget`.
+
+## 0.3.5+3
+
+* Make sure to post javascript channel messages from the platform thread.
+
+## 0.3.5+2
+
+* Fix crash from `NavigationDelegate` on later versions of Android.
+
+## 0.3.5+1
+
+* Fix a bug where updates to onPageFinished were ignored.
+
+## 0.3.5
+
+* Added an onPageFinished callback.
+
+## 0.3.4
+
+* Support specifying navigation delegates that can prevent navigations from being executed.
+
+## 0.3.3+2
+
+* Exclude LongPress handler from semantics tree since it does nothing.
+
+## 0.3.3+1
+
+* Fixed a memory leak on Android - the WebView was not properly disposed.
+
+## 0.3.3
+
+* Add clearCache method to WebView controller.
+
+## 0.3.2+1
+
+* Log a more detailed warning at build time about the previous AndroidX
+  migration.
+
+## 0.3.2
+
+* Added CookieManager to interface with WebView cookies. Currently has the ability to clear cookies.
+
+## 0.3.1
+
+* Added JavaScript channels to facilitate message passing from JavaScript code running inside
+  the WebView to the Flutter app's Dart code.
+
+## 0.3.0
+
+* **Breaking change**. Migrate from the deprecated original Android Support
+  Library to AndroidX. This shouldn't result in any functional changes, but it
+  requires any Android apps using this plugin to [also
+  migrate](https://developer.android.com/jetpack/androidx/migrate) if they're
+  using the original support library.
+
+## 0.2.0
+
+* Added a evaluateJavascript method to WebView controller.
+* (BREAKING CHANGE) Renamed the `JavaScriptMode` enum to `JavascriptMode`, and the WebView `javasScriptMode` parameter to `javascriptMode`.
+
+## 0.1.2
+
+* Added a reload method to the WebView controller.
+
+## 0.1.1
+
+* Added a `currentUrl` accessor for the WebView controller to look up what URL
+  is being displayed.
+
+## 0.1.0+1
+
+* Fix null crash when initialUrl is unset on iOS.
+
+## 0.1.0
+
+* Add goBack, goForward, canGoBack, and canGoForward methods to the WebView controller.
+
+## 0.0.1+1
+
+* Fix case for "FLTWebViewFlutterPlugin" (iOS was failing to buld on case-sensitive file systems).
+
+## 0.0.1
+
+* Initial release.

+ 27 - 0
LICENSE

@@ -0,0 +1,27 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+//    * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+//    * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+//    * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

+ 36 - 0
README.md

@@ -0,0 +1,36 @@
+# WebView for Flutter (Developers Preview)
+
+[![pub package](https://img.shields.io/pub/v/webview_flutter.svg)](https://pub.dartlang.org/packages/webview_flutter)
+
+A Flutter plugin that provides a WebView widget.
+
+On iOS the WebView widget is backed by a [WKWebView](https://developer.apple.com/documentation/webkit/wkwebview);
+On Android the WebView widget is backed by a [WebView](https://developer.android.com/reference/android/webkit/WebView).
+
+## Developers Preview Status
+The plugin relies on Flutter's new mechanism for embedding Android and iOS views.
+As that mechanism is currently in a developers preview, this plugin should also be
+considered a developers preview.
+
+Known issues are tagged with the [platform-views](https://github.com/flutter/flutter/labels/a%3A%20platform-views) and/or [webview](https://github.com/flutter/flutter/labels/p%3A%20webview) labels.
+
+To use this plugin on iOS you need to opt-in for the embedded views preview by
+adding a boolean property to the app's `Info.plist` file, with the key `io.flutter.embedded_views_preview`
+and the value `YES`.
+
+## Keyboard support - not ready for production use
+Keyboard support within webviews is experimental. The Android version relies on some low-level knobs that have not been well tested
+on a broad spectrum of devices yet, and therefore **it is not recommended to rely on webview keyboard in production apps yet**.
+See the [webview-keyboard](https://github.com/flutter/flutter/issues?q=is%3Aopen+is%3Aissue+label%3A%22p%3A+webview-keyboard%22) for known issues with keyboard input.
+
+## Setup
+
+### iOS
+Opt-in to the embedded views preview by adding a boolean property to the app's `Info.plist` file
+with the key `io.flutter.embedded_views_preview` and the value `YES`.
+
+## Usage
+Add `webview_flutter` as a [dependency in your pubspec.yaml file](https://flutter.io/platform-plugins/).
+
+You can now include a WebView widget in your widget tree.
+See the WebView widget's Dartdoc for more details on how to use the widget.

+ 29 - 0
android/android-webview_flutter.iml

@@ -0,0 +1,29 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<module version="4">
+  <component name="FacetManager">
+    <facet type="android-gradle" name="Android-Gradle">
+      <configuration>
+        <option name="GRADLE_PROJECT_PATH" value=":webview_flutter" />
+        <option name="LAST_SUCCESSFUL_SYNC_AGP_VERSION" value="3.3.0" />
+        <option name="LAST_KNOWN_AGP_VERSION" value="3.3.0" />
+      </configuration>
+    </facet>
+    <facet type="android" name="Android">
+      <configuration>
+        <option name="SELECTED_BUILD_VARIANT" value="debug" />
+        <option name="ASSEMBLE_TASK_NAME" value="assembleDebug" />
+        <option name="COMPILE_JAVA_TASK_NAME" value="compileDebugSources" />
+        <afterSyncTasks>
+          <task>generateDebugSources</task>
+        </afterSyncTasks>
+        <option name="ALLOW_USER_CONFIGURATION" value="false" />
+        <option name="MANIFEST_FILE_RELATIVE_PATH" value="/src/main/AndroidManifest.xml" />
+        <option name="RES_FOLDER_RELATIVE_PATH" value="/src/main/res" />
+        <option name="RES_FOLDERS_RELATIVE_PATH" value="file://$USER_HOME$/Desktop/flutter/i2-school-app/build/webview_flutter/generated/res/rs/debug;file://$USER_HOME$/Desktop/flutter/i2-school-app/build/webview_flutter/generated/res/resValues/debug" />
+        <option name="TEST_RES_FOLDERS_RELATIVE_PATH" value="" />
+        <option name="ASSETS_FOLDER_RELATIVE_PATH" value="/src/main/assets" />
+        <option name="PROJECT_TYPE" value="1" />
+      </configuration>
+    </facet>
+  </component>
+</module>

+ 39 - 0
android/build.gradle

@@ -0,0 +1,39 @@
+group 'io.flutter.plugins.webviewflutter'
+version '1.0-SNAPSHOT'
+
+buildscript {
+    repositories {
+        google()
+        jcenter()
+    }
+
+    dependencies {
+        classpath 'com.android.tools.build:gradle:3.3.0'
+    }
+}
+
+rootProject.allprojects {
+    repositories {
+        google()
+        jcenter()
+    }
+}
+
+apply plugin: 'com.android.library'
+
+android {
+    compileSdkVersion 28
+
+    defaultConfig {
+        minSdkVersion 16
+        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
+    }
+    lintOptions {
+        disable 'InvalidPackage'
+    }
+
+    dependencies {
+        implementation 'androidx.annotation:annotation:1.0.0'
+        implementation 'androidx.webkit:webkit:1.0.0'
+    }
+}

+ 1 - 0
android/settings.gradle

@@ -0,0 +1 @@
+rootProject.name = 'webview_flutter'

+ 2 - 0
android/src/main/AndroidManifest.xml

@@ -0,0 +1,2 @@
+<manifest package="io.flutter.plugins.webviewflutter">
+</manifest>

+ 143 - 0
android/src/main/java/io/flutter/plugins/webviewflutter/DisplayListenerProxy.java

@@ -0,0 +1,143 @@
+package io.flutter.plugins.webviewflutter;
+
+import static android.hardware.display.DisplayManager.DisplayListener;
+
+import android.annotation.TargetApi;
+import android.hardware.display.DisplayManager;
+import android.os.Build;
+import android.util.Log;
+import java.lang.reflect.Field;
+import java.util.ArrayList;
+
+/**
+ * Works around an Android WebView bug by filtering some DisplayListener invocations.
+ *
+ * <p>Older Android WebView versions had assumed that when {@link DisplayListener#onDisplayChanged}
+ * is invoked, the display ID it is provided is of a valid display. However it turns out that when a
+ * display is removed Android may call onDisplayChanged with the ID of the removed display, in this
+ * case the Android WebView code tries to fetch and use the display with this ID and crashes with an
+ * NPE.
+ *
+ * <p>This issue was fixed in the Android WebView code in
+ * https://chromium-review.googlesource.com/517913 which is available starting WebView version
+ * 58.0.3029.125 however older webviews in the wild still have this issue.
+ *
+ * <p>Since Flutter removes virtual displays whenever a platform view is resized the webview crash
+ * is more likely to happen than other apps. And users were reporting this issue see:
+ * https://github.com/flutter/flutter/issues/30420
+ *
+ * <p>This class works around the webview bug by unregistering the WebView's DisplayListener, and
+ * instead registering its own DisplayListener which delegates the callbacks to the WebView's
+ * listener unless it's a onDisplayChanged for an invalid display.
+ *
+ * <p>I did not find a clean way to get a handle of the WebView's DisplayListener so I'm using
+ * reflection to fetch all registered listeners before and after initializing a webview. In the
+ * first initialization of a webview within the process the difference between the lists is the
+ * webview's display listener.
+ */
+@TargetApi(Build.VERSION_CODES.KITKAT)
+class DisplayListenerProxy {
+  private static final String TAG = "DisplayListenerProxy";
+
+  private ArrayList<DisplayListener> listenersBeforeWebView;
+
+  /** Should be called prior to the webview's initialization. */
+  void onPreWebViewInitialization(DisplayManager displayManager) {
+    listenersBeforeWebView = yoinkDisplayListeners(displayManager);
+  }
+
+  /** Should be called after the webview's initialization. */
+  void onPostWebViewInitialization(final DisplayManager displayManager) {
+    final ArrayList<DisplayListener> webViewListeners = yoinkDisplayListeners(displayManager);
+    // We recorded the list of listeners prior to initializing webview, any new listeners we see
+    // after initializing the webview are listeners added by the webview.
+    webViewListeners.removeAll(listenersBeforeWebView);
+
+    if (webViewListeners.isEmpty()) {
+      // The Android WebView registers a single display listener per process (even if there
+      // are multiple WebView instances) so this list is expected to be non-empty only the
+      // first time a webview is initialized.
+      // Note that in an add2app scenario if the application had instantiated a non Flutter
+      // WebView prior to instantiating the Flutter WebView we are not able to get a reference
+      // to the WebView's display listener and can't work around the bug.
+      //
+      // This means that webview resizes in add2app Flutter apps with a non Flutter WebView
+      // running on a system with a webview prior to 58.0.3029.125 may crash (the Android's
+      // behavior seems to be racy so it doesn't always happen).
+      return;
+    }
+
+    for (DisplayListener webViewListener : webViewListeners) {
+      // Note that while DisplayManager.unregisterDisplayListener throws when given an
+      // unregistered listener, this isn't an issue as the WebView code never calls
+      // unregisterDisplayListener.
+      displayManager.unregisterDisplayListener(webViewListener);
+
+      // We never explicitly unregister this listener as the webview's listener is never
+      // unregistered (it's released when the process is terminated).
+      displayManager.registerDisplayListener(
+          new DisplayListener() {
+            @Override
+            public void onDisplayAdded(int displayId) {
+              for (DisplayListener webViewListener : webViewListeners) {
+                webViewListener.onDisplayAdded(displayId);
+              }
+            }
+
+            @Override
+            public void onDisplayRemoved(int displayId) {
+              for (DisplayListener webViewListener : webViewListeners) {
+                webViewListener.onDisplayRemoved(displayId);
+              }
+            }
+
+            @Override
+            public void onDisplayChanged(int displayId) {
+              if (displayManager.getDisplay(displayId) == null) {
+                return;
+              }
+              for (DisplayListener webViewListener : webViewListeners) {
+                webViewListener.onDisplayChanged(displayId);
+              }
+            }
+          },
+          null);
+    }
+  }
+
+  @SuppressWarnings({"unchecked", "PrivateApi"})
+  private static ArrayList<DisplayListener> yoinkDisplayListeners(DisplayManager displayManager) {
+    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
+      // We cannot use reflection on Android P, but it shouldn't matter as it shipped
+      // with WebView 66.0.3359.158 and the WebView version the bug this code is working around was
+      // fixed in 61.0.3116.0.
+      return new ArrayList<>();
+    }
+    try {
+      Field displayManagerGlobalField = DisplayManager.class.getDeclaredField("mGlobal");
+      displayManagerGlobalField.setAccessible(true);
+      Object displayManagerGlobal = displayManagerGlobalField.get(displayManager);
+      Field displayListenersField =
+          displayManagerGlobal.getClass().getDeclaredField("mDisplayListeners");
+      displayListenersField.setAccessible(true);
+      ArrayList<Object> delegates =
+          (ArrayList<Object>) displayListenersField.get(displayManagerGlobal);
+
+      Field listenerField = null;
+      ArrayList<DisplayManager.DisplayListener> listeners = new ArrayList<>();
+      for (Object delegate : delegates) {
+        if (listenerField == null) {
+          listenerField = delegate.getClass().getField("mListener");
+          listenerField.setAccessible(true);
+        }
+        DisplayManager.DisplayListener listener =
+            (DisplayManager.DisplayListener) listenerField.get(delegate);
+        listeners.add(listener);
+      }
+      return listeners;
+    } catch (NoSuchFieldException | IllegalAccessException e) {
+      Log.w(TAG, "Could not extract WebView's display listeners. " + e);
+      return new ArrayList<>();
+    }
+  }
+}

+ 56 - 0
android/src/main/java/io/flutter/plugins/webviewflutter/FlutterCookieManager.java

@@ -0,0 +1,56 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+package io.flutter.plugins.webviewflutter;
+
+import android.os.Build;
+import android.os.Build.VERSION_CODES;
+import android.webkit.CookieManager;
+import android.webkit.ValueCallback;
+import io.flutter.plugin.common.BinaryMessenger;
+import io.flutter.plugin.common.MethodCall;
+import io.flutter.plugin.common.MethodChannel;
+import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
+import io.flutter.plugin.common.MethodChannel.Result;
+
+class FlutterCookieManager implements MethodCallHandler {
+  private final MethodChannel methodChannel;
+
+  FlutterCookieManager(BinaryMessenger messenger) {
+    methodChannel = new MethodChannel(messenger, "plugins.flutter.io/cookie_manager");
+    methodChannel.setMethodCallHandler(this);
+  }
+
+  @Override
+  public void onMethodCall(MethodCall methodCall, Result result) {
+    switch (methodCall.method) {
+      case "clearCookies":
+        clearCookies(result);
+        break;
+      default:
+        result.notImplemented();
+    }
+  }
+
+  void dispose() {
+    methodChannel.setMethodCallHandler(null);
+  }
+
+  private static void clearCookies(final Result result) {
+    CookieManager cookieManager = CookieManager.getInstance();
+    final boolean hasCookies = cookieManager.hasCookies();
+    if (Build.VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
+      cookieManager.removeAllCookies(
+          new ValueCallback<Boolean>() {
+            @Override
+            public void onReceiveValue(Boolean value) {
+              result.success(hasCookies);
+            }
+          });
+    } else {
+      cookieManager.removeAllCookie();
+      result.success(hasCookies);
+    }
+  }
+}

+ 325 - 0
android/src/main/java/io/flutter/plugins/webviewflutter/FlutterWebView.java

@@ -0,0 +1,325 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+package io.flutter.plugins.webviewflutter;
+
+import android.annotation.TargetApi;
+import android.content.Context;
+import android.hardware.display.DisplayManager;
+import android.os.Build;
+import android.os.Handler;
+import android.view.View;
+import android.webkit.WebStorage;
+import android.webkit.WebViewClient;
+import io.flutter.plugin.common.BinaryMessenger;
+import io.flutter.plugin.common.MethodCall;
+import io.flutter.plugin.common.MethodChannel;
+import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
+import io.flutter.plugin.common.MethodChannel.Result;
+import io.flutter.plugin.platform.PlatformView;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+
+public class FlutterWebView implements PlatformView, MethodCallHandler {
+  private static final String JS_CHANNEL_NAMES_FIELD = "javascriptChannelNames";
+  private final InputAwareWebView webView;
+  private final MethodChannel methodChannel;
+  private final FlutterWebViewClient flutterWebViewClient;
+  private final Handler platformThreadHandler;
+
+  @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
+  @SuppressWarnings("unchecked")
+  FlutterWebView(
+      final Context context,
+      BinaryMessenger messenger,
+      int id,
+      Map<String, Object> params,
+      View containerView) {
+
+    DisplayListenerProxy displayListenerProxy = new DisplayListenerProxy();
+    DisplayManager displayManager =
+        (DisplayManager) context.getSystemService(Context.DISPLAY_SERVICE);
+    displayListenerProxy.onPreWebViewInitialization(displayManager);
+    webView = new InputAwareWebView(context, containerView);
+    displayListenerProxy.onPostWebViewInitialization(displayManager);
+
+    platformThreadHandler = new Handler(context.getMainLooper());
+    // Allow local storage.
+    webView.getSettings().setDomStorageEnabled(true);
+    webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
+	webView.getSettings().setMixedContentMode(webView.getSettings().MIXED_CONTENT_ALWAYS_ALLOW);
+
+    methodChannel = new MethodChannel(messenger, "plugins.flutter.io/webview_" + id);
+    methodChannel.setMethodCallHandler(this);
+
+    flutterWebViewClient = new FlutterWebViewClient(methodChannel);
+    applySettings((Map<String, Object>) params.get("settings"));
+
+    if (params.containsKey(JS_CHANNEL_NAMES_FIELD)) {
+      registerJavaScriptChannelNames((List<String>) params.get(JS_CHANNEL_NAMES_FIELD));
+    }
+
+    updateAutoMediaPlaybackPolicy((Integer) params.get("autoMediaPlaybackPolicy"));
+    if (params.containsKey("userAgent")) {
+      String userAgent = (String) params.get("userAgent");
+      updateUserAgent(userAgent);
+    }
+    if (params.containsKey("initialUrl")) {
+      String url = (String) params.get("initialUrl");
+      webView.loadUrl(url);
+    }
+  }
+
+  @Override
+  public View getView() {
+    return webView;
+  }
+
+  // @Override
+  // This is overriding a method that hasn't rolled into stable Flutter yet. Including the
+  // annotation would cause compile time failures in versions of Flutter too old to include the new
+  // method. However leaving it raw like this means that the method will be ignored in old versions
+  // of Flutter but used as an override anyway wherever it's actually defined.
+  // TODO(mklim): Add the @Override annotation once flutter/engine#9727 rolls to stable.
+  public void onInputConnectionUnlocked() {
+    webView.unlockInputConnection();
+  }
+
+  // @Override
+  // This is overriding a method that hasn't rolled into stable Flutter yet. Including the
+  // annotation would cause compile time failures in versions of Flutter too old to include the new
+  // method. However leaving it raw like this means that the method will be ignored in old versions
+  // of Flutter but used as an override anyway wherever it's actually defined.
+  // TODO(mklim): Add the @Override annotation once flutter/engine#9727 rolls to stable.
+  public void onInputConnectionLocked() {
+    webView.lockInputConnection();
+  }
+
+  // @Override
+  // This is overriding a method that hasn't rolled into stable Flutter yet. Including the
+  // annotation would cause compile time failures in versions of Flutter too old to include the new
+  // method. However leaving it raw like this means that the method will be ignored in old versions
+  // of Flutter but used as an override anyway wherever it's actually defined.
+  // TODO(mklim): Add the @Override annotation once stable passes v1.10.9.
+  public void onFlutterViewAttached(View flutterView) {
+    webView.setContainerView(flutterView);
+  }
+
+  // @Override
+  // This is overriding a method that hasn't rolled into stable Flutter yet. Including the
+  // annotation would cause compile time failures in versions of Flutter too old to include the new
+  // method. However leaving it raw like this means that the method will be ignored in old versions
+  // of Flutter but used as an override anyway wherever it's actually defined.
+  // TODO(mklim): Add the @Override annotation once stable passes v1.10.9.
+  public void onFlutterViewDetached() {
+    webView.setContainerView(null);
+  }
+
+  @Override
+  public void onMethodCall(MethodCall methodCall, Result result) {
+    switch (methodCall.method) {
+      case "loadUrl":
+        loadUrl(methodCall, result);
+        break;
+      case "updateSettings":
+        updateSettings(methodCall, result);
+        break;
+      case "canGoBack":
+        canGoBack(result);
+        break;
+      case "canGoForward":
+        canGoForward(result);
+        break;
+      case "goBack":
+        goBack(result);
+        break;
+      case "goForward":
+        goForward(result);
+        break;
+      case "reload":
+        reload(result);
+        break;
+      case "currentUrl":
+        currentUrl(result);
+        break;
+      case "evaluateJavascript":
+        evaluateJavaScript(methodCall, result);
+        break;
+      case "addJavascriptChannels":
+        addJavaScriptChannels(methodCall, result);
+        break;
+      case "removeJavascriptChannels":
+        removeJavaScriptChannels(methodCall, result);
+        break;
+      case "clearCache":
+        clearCache(result);
+        break;
+      case "getTitle":
+        getTitle(result);
+        break;
+      default:
+        result.notImplemented();
+    }
+  }
+
+  @SuppressWarnings("unchecked")
+  private void loadUrl(MethodCall methodCall, Result result) {
+    Map<String, Object> request = (Map<String, Object>) methodCall.arguments;
+    String url = (String) request.get("url");
+    Map<String, String> headers = (Map<String, String>) request.get("headers");
+    if (headers == null) {
+      headers = Collections.emptyMap();
+    }
+    webView.loadUrl(url, headers);
+    result.success(null);
+  }
+
+  private void canGoBack(Result result) {
+    result.success(webView.canGoBack());
+  }
+
+  private void canGoForward(Result result) {
+    result.success(webView.canGoForward());
+  }
+
+  private void goBack(Result result) {
+    if (webView.canGoBack()) {
+      webView.goBack();
+    }
+    result.success(null);
+  }
+
+  private void goForward(Result result) {
+    if (webView.canGoForward()) {
+      webView.goForward();
+    }
+    result.success(null);
+  }
+
+  private void reload(Result result) {
+    webView.reload();
+    result.success(null);
+  }
+
+  private void currentUrl(Result result) {
+    result.success(webView.getUrl());
+  }
+
+  @SuppressWarnings("unchecked")
+  private void updateSettings(MethodCall methodCall, Result result) {
+    applySettings((Map<String, Object>) methodCall.arguments);
+    result.success(null);
+  }
+
+  @TargetApi(Build.VERSION_CODES.KITKAT)
+  private void evaluateJavaScript(MethodCall methodCall, final Result result) {
+    String jsString = (String) methodCall.arguments;
+    if (jsString == null) {
+      throw new UnsupportedOperationException("JavaScript string cannot be null");
+    }
+    webView.evaluateJavascript(
+        jsString,
+        new android.webkit.ValueCallback<String>() {
+          @Override
+          public void onReceiveValue(String value) {
+            result.success(value);
+          }
+        });
+  }
+
+  @SuppressWarnings("unchecked")
+  private void addJavaScriptChannels(MethodCall methodCall, Result result) {
+    List<String> channelNames = (List<String>) methodCall.arguments;
+    registerJavaScriptChannelNames(channelNames);
+    result.success(null);
+  }
+
+  @SuppressWarnings("unchecked")
+  private void removeJavaScriptChannels(MethodCall methodCall, Result result) {
+    List<String> channelNames = (List<String>) methodCall.arguments;
+    for (String channelName : channelNames) {
+      webView.removeJavascriptInterface(channelName);
+    }
+    result.success(null);
+  }
+
+  private void clearCache(Result result) {
+    webView.clearCache(true);
+    WebStorage.getInstance().deleteAllData();
+    result.success(null);
+  }
+
+  private void getTitle(Result result) {
+    result.success(webView.getTitle());
+  }
+
+  private void applySettings(Map<String, Object> settings) {
+    for (String key : settings.keySet()) {
+      switch (key) {
+        case "jsMode":
+          updateJsMode((Integer) settings.get(key));
+          break;
+        case "hasNavigationDelegate":
+          final boolean hasNavigationDelegate = (boolean) settings.get(key);
+
+          final WebViewClient webViewClient =
+              flutterWebViewClient.createWebViewClient(hasNavigationDelegate);
+
+          webView.setWebViewClient(webViewClient);
+          break;
+        case "debuggingEnabled":
+          final boolean debuggingEnabled = (boolean) settings.get(key);
+
+          webView.setWebContentsDebuggingEnabled(debuggingEnabled);
+          break;
+        case "gestureNavigationEnabled":
+          break;
+        case "userAgent":
+          updateUserAgent((String) settings.get(key));
+          break;
+        default:
+          throw new IllegalArgumentException("Unknown WebView setting: " + key);
+      }
+    }
+  }
+
+  private void updateJsMode(int mode) {
+    switch (mode) {
+      case 0: // disabled
+        webView.getSettings().setJavaScriptEnabled(false);
+        break;
+      case 1: // unrestricted
+        webView.getSettings().setJavaScriptEnabled(true);
+        break;
+      default:
+        throw new IllegalArgumentException("Trying to set unknown JavaScript mode: " + mode);
+    }
+  }
+
+  private void updateAutoMediaPlaybackPolicy(int mode) {
+    // This is the index of the AutoMediaPlaybackPolicy enum, index 1 is always_allow, for all
+    // other values we require a user gesture.
+    boolean requireUserGesture = mode != 1;
+    webView.getSettings().setMediaPlaybackRequiresUserGesture(requireUserGesture);
+  }
+
+  private void registerJavaScriptChannelNames(List<String> channelNames) {
+    for (String channelName : channelNames) {
+      webView.addJavascriptInterface(
+          new JavaScriptChannel(methodChannel, channelName, platformThreadHandler), channelName);
+    }
+  }
+
+  private void updateUserAgent(String userAgent) {
+    webView.getSettings().setUserAgentString(userAgent);
+  }
+
+  @Override
+  public void dispose() {
+    methodChannel.setMethodCallHandler(null);
+    webView.dispose();
+    webView.destroy();
+  }
+}

+ 204 - 0
android/src/main/java/io/flutter/plugins/webviewflutter/FlutterWebViewClient.java

@@ -0,0 +1,204 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+package io.flutter.plugins.webviewflutter;
+
+import android.annotation.TargetApi;
+import android.graphics.Bitmap;
+import android.os.Build;
+import android.util.Log;
+import android.view.KeyEvent;
+import android.webkit.WebResourceRequest;
+import android.webkit.WebView;
+import android.webkit.WebViewClient;
+import androidx.webkit.WebViewClientCompat;
+import io.flutter.plugin.common.MethodChannel;
+import java.util.HashMap;
+import java.util.Map;
+
+// We need to use WebViewClientCompat to get
+// shouldOverrideUrlLoading(WebView view, WebResourceRequest request)
+// invoked by the webview on older Android devices, without it pages that use iframes will
+// be broken when a navigationDelegate is set on Android version earlier than N.
+class FlutterWebViewClient {
+  private static final String TAG = "FlutterWebViewClient";
+  private final MethodChannel methodChannel;
+  private boolean hasNavigationDelegate;
+
+  FlutterWebViewClient(MethodChannel methodChannel) {
+    this.methodChannel = methodChannel;
+  }
+
+  @TargetApi(Build.VERSION_CODES.LOLLIPOP)
+  private boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
+    if (!hasNavigationDelegate) {
+      return false;
+    }
+    notifyOnNavigationRequest(
+        request.getUrl().toString(), request.getRequestHeaders(), view, request.isForMainFrame());
+    // We must make a synchronous decision here whether to allow the navigation or not,
+    // if the Dart code has set a navigation delegate we want that delegate to decide whether
+    // to navigate or not, and as we cannot get a response from the Dart delegate synchronously we
+    // return true here to block the navigation, if the Dart delegate decides to allow the
+    // navigation the plugin will later make an addition loadUrl call for this url.
+    //
+    // Since we cannot call loadUrl for a subframe, we currently only allow the delegate to stop
+    // navigations that target the main frame, if the request is not for the main frame
+    // we just return false to allow the navigation.
+    //
+    // For more details see: https://github.com/flutter/flutter/issues/25329#issuecomment-464863209
+    return request.isForMainFrame();
+  }
+
+  private boolean shouldOverrideUrlLoading(WebView view, String url) {
+    if (!hasNavigationDelegate) {
+      return false;
+    }
+    // This version of shouldOverrideUrlLoading is only invoked by the webview on devices with
+    // webview versions  earlier than 67(it is also invoked when hasNavigationDelegate is false).
+    // On these devices we cannot tell whether the navigation is targeted to the main frame or not.
+    // We proceed assuming that the navigation is targeted to the main frame. If the page had any
+    // frames they will be loaded in the main frame instead.
+    Log.w(
+        TAG,
+        "Using a navigationDelegate with an old webview implementation, pages with frames or iframes will not work");
+    notifyOnNavigationRequest(url, null, view, true);
+    return true;
+  }
+
+  private void onPageStarted(WebView view, String url) {
+    Map<String, Object> args = new HashMap<>();
+    args.put("url", url);
+    methodChannel.invokeMethod("onPageStarted", args);
+  }
+
+  private void onPageFinished(WebView view, String url) {
+    Map<String, Object> args = new HashMap<>();
+    args.put("url", url);
+    methodChannel.invokeMethod("onPageFinished", args);
+  }
+
+  private void notifyOnNavigationRequest(
+      String url, Map<String, String> headers, WebView webview, boolean isMainFrame) {
+    HashMap<String, Object> args = new HashMap<>();
+    args.put("url", url);
+    args.put("isForMainFrame", isMainFrame);
+    if (isMainFrame) {
+      methodChannel.invokeMethod(
+          "navigationRequest", args, new OnNavigationRequestResult(url, headers, webview));
+    } else {
+      methodChannel.invokeMethod("navigationRequest", args);
+    }
+  }
+
+  // This method attempts to avoid using WebViewClientCompat due to bug
+  // https://bugs.chromium.org/p/chromium/issues/detail?id=925887. Also, see
+  // https://github.com/flutter/flutter/issues/29446.
+  WebViewClient createWebViewClient(boolean hasNavigationDelegate) {
+    this.hasNavigationDelegate = hasNavigationDelegate;
+
+    if (!hasNavigationDelegate || android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
+      return internalCreateWebViewClient();
+    }
+
+    return internalCreateWebViewClientCompat();
+  }
+
+  private WebViewClient internalCreateWebViewClient() {
+    return new WebViewClient() {
+      @TargetApi(Build.VERSION_CODES.N)
+      @Override
+      public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
+        return FlutterWebViewClient.this.shouldOverrideUrlLoading(view, request);
+      }
+
+      @Override
+      public void onPageStarted(WebView view, String url, Bitmap favicon) {
+        FlutterWebViewClient.this.onPageStarted(view, url);
+      }
+
+      @Override
+      public void onPageFinished(WebView view, String url) {
+        FlutterWebViewClient.this.onPageFinished(view, url);
+      }
+
+      @Override
+      public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
+        // Deliberately empty. Occasionally the webview will mark events as having failed to be
+        // handled even though they were handled. We don't want to propagate those as they're not
+        // truly lost.
+      }
+    };
+  }
+
+  private WebViewClientCompat internalCreateWebViewClientCompat() {
+    return new WebViewClientCompat() {
+      @Override
+      public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
+        return FlutterWebViewClient.this.shouldOverrideUrlLoading(view, request);
+      }
+
+      @Override
+      public boolean shouldOverrideUrlLoading(WebView view, String url) {
+        return FlutterWebViewClient.this.shouldOverrideUrlLoading(view, url);
+      }
+
+      @Override
+      public void onPageStarted(WebView view, String url, Bitmap favicon) {
+        FlutterWebViewClient.this.onPageStarted(view, url);
+      }
+
+      @Override
+      public void onPageFinished(WebView view, String url) {
+        FlutterWebViewClient.this.onPageFinished(view, url);
+      }
+
+      @Override
+      public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
+        // Deliberately empty. Occasionally the webview will mark events as having failed to be
+        // handled even though they were handled. We don't want to propagate those as they're not
+        // truly lost.
+      }
+    };
+  }
+
+  private static class OnNavigationRequestResult implements MethodChannel.Result {
+    private final String url;
+    private final Map<String, String> headers;
+    private final WebView webView;
+
+    private OnNavigationRequestResult(String url, Map<String, String> headers, WebView webView) {
+      this.url = url;
+      this.headers = headers;
+      this.webView = webView;
+    }
+
+    @Override
+    public void success(Object shouldLoad) {
+      Boolean typedShouldLoad = (Boolean) shouldLoad;
+      if (typedShouldLoad) {
+        loadUrl();
+      }
+    }
+
+    @Override
+    public void error(String errorCode, String s1, Object o) {
+      throw new IllegalStateException("navigationRequest calls must succeed");
+    }
+
+    @Override
+    public void notImplemented() {
+      throw new IllegalStateException(
+          "navigationRequest must be implemented by the webview method channel");
+    }
+
+    private void loadUrl() {
+      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
+        webView.loadUrl(url, headers);
+      } else {
+        webView.loadUrl(url);
+      }
+    }
+  }
+}

+ 189 - 0
android/src/main/java/io/flutter/plugins/webviewflutter/InputAwareWebView.java

@@ -0,0 +1,189 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+package io.flutter.plugins.webviewflutter;
+
+import static android.content.Context.INPUT_METHOD_SERVICE;
+
+import android.content.Context;
+import android.util.Log;
+import android.view.View;
+import android.view.inputmethod.InputMethodManager;
+import android.webkit.WebView;
+
+/**
+ * A WebView subclass that mirrors the same implementation hacks that the system WebView does in
+ * order to correctly create an InputConnection.
+ *
+ * <p>These hacks are only needed in Android versions below N and exist to create an InputConnection
+ * on the WebView's dedicated input, or IME, thread. The majority of this proxying logic is in
+ * {@link #checkInputConnectionProxy}.
+ *
+ * <p>See also {@link ThreadedInputConnectionProxyAdapterView}.
+ */
+final class InputAwareWebView extends WebView {
+  private static final String TAG = "InputAwareWebView";
+  private View threadedInputConnectionProxyView;
+  private ThreadedInputConnectionProxyAdapterView proxyAdapterView;
+  private View containerView;
+
+  InputAwareWebView(Context context, View containerView) {
+    super(context);
+    this.containerView = containerView;
+  }
+
+  void setContainerView(View containerView) {
+    this.containerView = containerView;
+
+    if (proxyAdapterView == null) {
+      return;
+    }
+
+    Log.w(TAG, "The containerView has changed while the proxyAdapterView exists.");
+    if (containerView != null) {
+      setInputConnectionTarget(proxyAdapterView);
+    }
+  }
+
+  /**
+   * Set our proxy adapter view to use its cached input connection instead of creating new ones.
+   *
+   * <p>This is used to avoid losing our input connection when the virtual display is resized.
+   */
+  void lockInputConnection() {
+    if (proxyAdapterView == null) {
+      return;
+    }
+
+    proxyAdapterView.setLocked(true);
+  }
+
+  /** Sets the proxy adapter view back to its default behavior. */
+  void unlockInputConnection() {
+    if (proxyAdapterView == null) {
+      return;
+    }
+
+    proxyAdapterView.setLocked(false);
+  }
+
+  /** Restore the original InputConnection, if needed. */
+  void dispose() {
+    resetInputConnection();
+  }
+
+  /**
+   * Creates an InputConnection from the IME thread when needed.
+   *
+   * <p>We only need to create a {@link ThreadedInputConnectionProxyAdapterView} and create an
+   * InputConnectionProxy on the IME thread when WebView is doing the same thing. So we rely on the
+   * system calling this method for WebView's proxy view in order to know when we need to create our
+   * own.
+   *
+   * <p>This method would normally be called for any View that used the InputMethodManager. We rely
+   * on flutter/engine filtering the calls we receive down to the ones in our hierarchy and the
+   * system WebView in order to know whether or not the system WebView expects an InputConnection on
+   * the IME thread.
+   */
+  @Override
+  public boolean checkInputConnectionProxy(final View view) {
+    // Check to see if the view param is WebView's ThreadedInputConnectionProxyView.
+    View previousProxy = threadedInputConnectionProxyView;
+    threadedInputConnectionProxyView = view;
+    if (previousProxy == view) {
+      // This isn't a new ThreadedInputConnectionProxyView. Ignore it.
+      return super.checkInputConnectionProxy(view);
+    }
+    if (containerView == null) {
+      Log.e(
+          TAG,
+          "Can't create a proxy view because there's no container view. Text input may not work.");
+      return super.checkInputConnectionProxy(view);
+    }
+
+    // We've never seen this before, so we make the assumption that this is WebView's
+    // ThreadedInputConnectionProxyView. We are making the assumption that the only view that could
+    // possibly be interacting with the IMM here is WebView's ThreadedInputConnectionProxyView.
+    proxyAdapterView =
+        new ThreadedInputConnectionProxyAdapterView(
+            /*containerView=*/ containerView,
+            /*targetView=*/ view,
+            /*imeHandler=*/ view.getHandler());
+    setInputConnectionTarget(/*targetView=*/ proxyAdapterView);
+    return super.checkInputConnectionProxy(view);
+  }
+
+  /**
+   * Ensure that input creation happens back on {@link #containerView}'s thread once this view no
+   * longer has focus.
+   *
+   * <p>The logic in {@link #checkInputConnectionProxy} forces input creation to happen on Webview's
+   * thread for all connections. We undo it here so users will be able to go back to typing in
+   * Flutter UIs as expected.
+   */
+  @Override
+  public void clearFocus() {
+    super.clearFocus();
+    resetInputConnection();
+  }
+
+  /**
+   * Ensure that input creation happens back on {@link #containerView}.
+   *
+   * <p>The logic in {@link #checkInputConnectionProxy} forces input creation to happen on Webview's
+   * thread for all connections. We undo it here so users will be able to go back to typing in
+   * Flutter UIs as expected.
+   */
+  private void resetInputConnection() {
+    if (proxyAdapterView == null) {
+      // No need to reset the InputConnection to the default thread if we've never changed it.
+      return;
+    }
+    if (containerView == null) {
+      Log.e(TAG, "Can't reset the input connection to the container view because there is none.");
+      return;
+    }
+    setInputConnectionTarget(/*targetView=*/ containerView);
+  }
+
+  /**
+   * This is the crucial trick that gets the InputConnection creation to happen on the correct
+   * thread pre Android N.
+   * https://cs.chromium.org/chromium/src/content/public/android/java/src/org/chromium/content/browser/input/ThreadedInputConnectionFactory.java?l=169&rcl=f0698ee3e4483fad5b0c34159276f71cfaf81f3a
+   *
+   * <p>{@code targetView} should have a {@link View#getHandler} method with the thread that future
+   * InputConnections should be created on.
+   */
+  private void setInputConnectionTarget(final View targetView) {
+    if (containerView == null) {
+      Log.e(
+          TAG,
+          "Can't set the input connection target because there is no containerView to use as a handler.");
+      return;
+    }
+
+    targetView.requestFocus();
+    containerView.post(
+        new Runnable() {
+          @Override
+          public void run() {
+            InputMethodManager imm =
+                (InputMethodManager) getContext().getSystemService(INPUT_METHOD_SERVICE);
+            // This is a hack to make InputMethodManager believe that the target view now has focus.
+            // As a result, InputMethodManager will think that targetView is focused, and will call
+            // getHandler() of the view when creating input connection.
+
+            // Step 1: Set targetView as InputMethodManager#mNextServedView. This does not affect
+            // the real window focus.
+            targetView.onWindowFocusChanged(true);
+
+            // Step 2: Have InputMethodManager focus in on targetView. As a result, IMM will call
+            // onCreateInputConnection() on targetView on the same thread as
+            // targetView.getHandler(). It will also call subsequent InputConnection methods on this
+            // thread. This is the IME thread in cases where targetView is our proxyAdapterView.
+            imm.isActive(containerView);
+          }
+        });
+  }
+}

+ 58 - 0
android/src/main/java/io/flutter/plugins/webviewflutter/JavaScriptChannel.java

@@ -0,0 +1,58 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+package io.flutter.plugins.webviewflutter;
+
+import android.os.Handler;
+import android.os.Looper;
+import android.webkit.JavascriptInterface;
+import io.flutter.plugin.common.MethodChannel;
+import java.util.HashMap;
+
+/**
+ * Added as a JavaScript interface to the WebView for any JavaScript channel that the Dart code sets
+ * up.
+ *
+ * <p>Exposes a single method named `postMessage` to JavaScript, which sends a message over a method
+ * channel to the Dart code.
+ */
+class JavaScriptChannel {
+  private final MethodChannel methodChannel;
+  private final String javaScriptChannelName;
+  private final Handler platformThreadHandler;
+
+  /**
+   * @param methodChannel the Flutter WebView method channel to which JS messages are sent
+   * @param javaScriptChannelName the name of the JavaScript channel, this is sent over the method
+   *     channel with each message to let the Dart code know which JavaScript channel the message
+   *     was sent through
+   */
+  JavaScriptChannel(
+      MethodChannel methodChannel, String javaScriptChannelName, Handler platformThreadHandler) {
+    this.methodChannel = methodChannel;
+    this.javaScriptChannelName = javaScriptChannelName;
+    this.platformThreadHandler = platformThreadHandler;
+  }
+
+  // Suppressing unused warning as this is invoked from JavaScript.
+  @SuppressWarnings("unused")
+  @JavascriptInterface
+  public void postMessage(final String message) {
+    Runnable postMessageRunnable =
+        new Runnable() {
+          @Override
+          public void run() {
+            HashMap<String, String> arguments = new HashMap<>();
+            arguments.put("channel", javaScriptChannelName);
+            arguments.put("message", message);
+            methodChannel.invokeMethod("javascriptChannelMessage", arguments);
+          }
+        };
+    if (platformThreadHandler.getLooper() == Looper.myLooper()) {
+      postMessageRunnable.run();
+    } else {
+      platformThreadHandler.post(postMessageRunnable);
+    }
+  }
+}

+ 112 - 0
android/src/main/java/io/flutter/plugins/webviewflutter/ThreadedInputConnectionProxyAdapterView.java

@@ -0,0 +1,112 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+package io.flutter.plugins.webviewflutter;
+
+import android.os.Handler;
+import android.os.IBinder;
+import android.view.View;
+import android.view.inputmethod.EditorInfo;
+import android.view.inputmethod.InputConnection;
+
+/**
+ * A fake View only exposed to InputMethodManager.
+ *
+ * <p>This follows a similar flow to Chromium's WebView (see
+ * https://cs.chromium.org/chromium/src/content/public/android/java/src/org/chromium/content/browser/input/ThreadedInputConnectionProxyView.java).
+ * WebView itself bounces its InputConnection around several different threads. We follow its logic
+ * here to get the same working connection.
+ *
+ * <p>This exists solely to forward input creation to WebView's ThreadedInputConnectionProxyView on
+ * the IME thread. The way that this is created in {@link
+ * InputAwareWebView#checkInputConnectionProxy} guarantees that we have a handle to
+ * ThreadedInputConnectionProxyView and {@link #onCreateInputConnection} is always called on the IME
+ * thread. We delegate to ThreadedInputConnectionProxyView there to get WebView's input connection.
+ */
+final class ThreadedInputConnectionProxyAdapterView extends View {
+  final Handler imeHandler;
+  final IBinder windowToken;
+  final View containerView;
+  final View rootView;
+  final View targetView;
+
+  private boolean triggerDelayed = true;
+  private boolean isLocked = false;
+  private InputConnection cachedConnection;
+
+  ThreadedInputConnectionProxyAdapterView(View containerView, View targetView, Handler imeHandler) {
+    super(containerView.getContext());
+    this.imeHandler = imeHandler;
+    this.containerView = containerView;
+    this.targetView = targetView;
+    windowToken = containerView.getWindowToken();
+    rootView = containerView.getRootView();
+    setFocusable(true);
+    setFocusableInTouchMode(true);
+    setVisibility(VISIBLE);
+  }
+
+  /** Returns whether or not this is currently asynchronously acquiring an input connection. */
+  boolean isTriggerDelayed() {
+    return triggerDelayed;
+  }
+
+  /** Sets whether or not this should use its previously cached input connection. */
+  void setLocked(boolean locked) {
+    isLocked = locked;
+  }
+
+  /**
+   * This is expected to be called on the IME thread. See the setup required for this in {@link
+   * InputAwareWebView#checkInputConnectionProxy(View)}.
+   *
+   * <p>Delegates to ThreadedInputConnectionProxyView to get WebView's input connection.
+   */
+  @Override
+  public InputConnection onCreateInputConnection(final EditorInfo outAttrs) {
+    triggerDelayed = false;
+    InputConnection inputConnection =
+        (isLocked) ? cachedConnection : targetView.onCreateInputConnection(outAttrs);
+    triggerDelayed = true;
+    cachedConnection = inputConnection;
+    return inputConnection;
+  }
+
+  @Override
+  public boolean checkInputConnectionProxy(View view) {
+    return true;
+  }
+
+  @Override
+  public boolean hasWindowFocus() {
+    // None of our views here correctly report they have window focus because of how we're embedding
+    // the platform view inside of a virtual display.
+    return true;
+  }
+
+  @Override
+  public View getRootView() {
+    return rootView;
+  }
+
+  @Override
+  public boolean onCheckIsTextEditor() {
+    return true;
+  }
+
+  @Override
+  public boolean isFocused() {
+    return true;
+  }
+
+  @Override
+  public IBinder getWindowToken() {
+    return windowToken;
+  }
+
+  @Override
+  public Handler getHandler() {
+    return imeHandler;
+  }
+}

+ 31 - 0
android/src/main/java/io/flutter/plugins/webviewflutter/WebViewFactory.java

@@ -0,0 +1,31 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+package io.flutter.plugins.webviewflutter;
+
+import android.content.Context;
+import android.view.View;
+import io.flutter.plugin.common.BinaryMessenger;
+import io.flutter.plugin.common.StandardMessageCodec;
+import io.flutter.plugin.platform.PlatformView;
+import io.flutter.plugin.platform.PlatformViewFactory;
+import java.util.Map;
+
+public final class WebViewFactory extends PlatformViewFactory {
+  private final BinaryMessenger messenger;
+  private final View containerView;
+
+  WebViewFactory(BinaryMessenger messenger, View containerView) {
+    super(StandardMessageCodec.INSTANCE);
+    this.messenger = messenger;
+    this.containerView = containerView;
+  }
+
+  @SuppressWarnings("unchecked")
+  @Override
+  public PlatformView create(Context context, int id, Object args) {
+    Map<String, Object> params = (Map<String, Object>) args;
+    return new FlutterWebView(context, messenger, id, params, containerView);
+  }
+}

+ 74 - 0
android/src/main/java/io/flutter/plugins/webviewflutter/WebViewFlutterPlugin.java

@@ -0,0 +1,74 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+package io.flutter.plugins.webviewflutter;
+
+import io.flutter.embedding.engine.plugins.FlutterPlugin;
+import io.flutter.plugin.common.BinaryMessenger;
+import io.flutter.plugin.common.PluginRegistry.Registrar;
+
+/**
+ * Java platform implementation of the webview_flutter plugin.
+ *
+ * <p>Register this in an add to app scenario to gracefully handle activity and context changes.
+ *
+ * <p>Call {@link #registerWith(Registrar)} to use the stable {@code io.flutter.plugin.common}
+ * package instead.
+ */
+public class WebViewFlutterPlugin implements FlutterPlugin {
+
+  private FlutterCookieManager flutterCookieManager;
+
+  /**
+   * Add an instance of this to {@link io.flutter.embedding.engine.plugins.PluginRegistry} to
+   * register it.
+   *
+   * <p>THIS PLUGIN CODE PATH DEPENDS ON A NEWER VERSION OF FLUTTER THAN THE ONE DEFINED IN THE
+   * PUBSPEC.YAML. Text input will fail on some Android devices unless this is used with at least
+   * flutter/flutter@1d4d63ace1f801a022ea9ec737bf8c15395588b9. Use the V1 embedding with {@link
+   * #registerWith(Registrar)} to use this plugin with older Flutter versions.
+   *
+   * <p>Registration should eventually be handled automatically by v2 of the
+   * GeneratedPluginRegistrant. https://github.com/flutter/flutter/issues/42694
+   */
+  public WebViewFlutterPlugin() {}
+
+  /**
+   * Registers a plugin implementation that uses the stable {@code io.flutter.plugin.common}
+   * package.
+   *
+   * <p>Calling this automatically initializes the plugin. However plugins initialized this way
+   * won't react to changes in activity or context, unlike {@link CameraPlugin}.
+   */
+  public static void registerWith(Registrar registrar) {
+    registrar
+        .platformViewRegistry()
+        .registerViewFactory(
+            "plugins.flutter.io/webview",
+            new WebViewFactory(registrar.messenger(), registrar.view()));
+    new FlutterCookieManager(registrar.messenger());
+  }
+
+  @Override
+  public void onAttachedToEngine(FlutterPluginBinding binding) {
+    BinaryMessenger messenger = binding.getFlutterEngine().getDartExecutor();
+    binding
+        .getFlutterEngine()
+        .getPlatformViewsController()
+        .getRegistry()
+        .registerViewFactory(
+            "plugins.flutter.io/webview", new WebViewFactory(messenger, /*containerView=*/ null));
+    flutterCookieManager = new FlutterCookieManager(messenger);
+  }
+
+  @Override
+  public void onDetachedFromEngine(FlutterPluginBinding binding) {
+    if (flutterCookieManager == null) {
+      return;
+    }
+
+    flutterCookieManager.dispose();
+    flutterCookieManager = null;
+  }
+}

+ 8 - 0
example/.metadata

@@ -0,0 +1,8 @@
+# This file tracks properties of this Flutter project.
+# Used by Flutter tool to assess capabilities and perform upgrades etc.
+#
+# This file should be version controlled and should not be manually edited.
+
+version:
+  revision: 1e5cb2d87f8542f9fbbd0f22d528823274be0acb
+  channel: master

+ 8 - 0
example/README.md

@@ -0,0 +1,8 @@
+# webview_flutter_example
+
+Demonstrates how to use the webview_flutter plugin.
+
+## Getting Started
+
+For help getting started with Flutter, view our online
+[documentation](https://flutter.io/).

+ 62 - 0
example/android/app/build.gradle

@@ -0,0 +1,62 @@
+def localProperties = new Properties()
+def localPropertiesFile = rootProject.file('local.properties')
+if (localPropertiesFile.exists()) {
+    localPropertiesFile.withReader('UTF-8') { reader ->
+        localProperties.load(reader)
+    }
+}
+
+def flutterRoot = localProperties.getProperty('flutter.sdk')
+if (flutterRoot == null) {
+    throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
+}
+
+def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
+if (flutterVersionCode == null) {
+    flutterVersionCode = '1'
+}
+
+def flutterVersionName = localProperties.getProperty('flutter.versionName')
+if (flutterVersionName == null) {
+    flutterVersionName = '1.0'
+}
+
+apply plugin: 'com.android.application'
+apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
+
+android {
+    compileSdkVersion 28
+
+    lintOptions {
+        disable 'InvalidPackage'
+    }
+
+    defaultConfig {
+        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
+        applicationId "io.flutter.plugins.webviewflutterexample"
+        minSdkVersion 16
+        targetSdkVersion 28
+        versionCode flutterVersionCode.toInteger()
+        versionName flutterVersionName
+        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
+    }
+
+    buildTypes {
+        release {
+            // TODO: Add your own signing config for the release build.
+            // Signing with the debug keys for now, so `flutter run --release` works.
+            signingConfig signingConfigs.debug
+        }
+    }
+}
+
+flutter {
+    source '../..'
+}
+
+dependencies {
+    testImplementation 'junit:junit:4.12'
+    androidTestImplementation 'androidx.test:runner:1.2.0'
+    androidTestImplementation 'androidx.test:rules:1.2.0'
+    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
+}

+ 5 - 0
example/android/app/gradle/wrapper/gradle-wrapper.properties

@@ -0,0 +1,5 @@
+distributionBase=GRADLE_USER_HOME
+distributionPath=wrapper/dists
+distributionUrl=https\://services.gradle.org/distributions/gradle-4.6-all.zip
+zipStoreBase=GRADLE_USER_HOME
+zipStorePath=wrapper/dists

+ 13 - 0
example/android/app/src/androidTestDebug/java/io/flutter/plugins/webviewflutterexample/EmbeddingV1ActivityTest.java

@@ -0,0 +1,13 @@
+package io.flutter.plugins.webviewflutterexample;
+
+import androidx.test.rule.ActivityTestRule;
+import dev.flutter.plugins.e2e.FlutterRunner;
+import org.junit.Rule;
+import org.junit.runner.RunWith;
+
+@RunWith(FlutterRunner.class)
+public class EmbeddingV1ActivityTest {
+  @Rule
+  public ActivityTestRule<EmbeddingV1Activity> rule =
+      new ActivityTestRule<>(EmbeddingV1Activity.class);
+}

+ 13 - 0
example/android/app/src/androidTestDebug/java/io/flutter/plugins/webviewflutterexample/MainActivityTest.java

@@ -0,0 +1,13 @@
+package io.flutter.plugins.webviewflutterexample;
+
+import androidx.test.rule.ActivityTestRule;
+import dev.flutter.plugins.e2e.FlutterRunner;
+import io.flutter.embedding.android.FlutterActivity;
+import org.junit.Rule;
+import org.junit.runner.RunWith;
+
+@RunWith(FlutterRunner.class)
+public class MainActivityTest {
+  @Rule
+  public ActivityTestRule<FlutterActivity> rule = new ActivityTestRule<>(FlutterActivity.class);
+}

+ 51 - 0
example/android/app/src/main/AndroidManifest.xml

@@ -0,0 +1,51 @@
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+  package="io.flutter.plugins.webviewflutterexample">
+
+  <!-- io.flutter.app.FlutterApplication is an android.app.Application that
+       calls FlutterMain.startInitialization(this); in its onCreate method.
+       In most cases you can leave this as-is, but you if you want to provide
+       additional functionality it is fine to subclass or reimplement
+       FlutterApplication and put your custom class here. -->
+  <application
+    android:icon="@mipmap/ic_launcher"
+    android:label="webview_flutter_example"
+    android:name="io.flutter.app.FlutterApplication">
+    <meta-data
+        android:name="flutterEmbedding"
+        android:value="2" />
+    <activity
+      android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density"
+      android:exported="true"
+      android:hardwareAccelerated="true"
+      android:launchMode="singleTop"
+      android:name=".EmbeddingV1Activity"
+      android:theme="@style/LaunchTheme"
+      android:windowSoftInputMode="adjustResize">
+      <!-- This keeps the window background of the activity showing
+           until Flutter renders its first frame. It can be removed if
+           there is no splash screen (such as the default splash screen
+           defined in @style/LaunchTheme). -->
+      <meta-data
+        android:name="io.flutter.app.android.SplashScreenUntilFirstFrame"
+        android:value="true"/>
+    </activity>
+    <activity
+      android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density"
+      android:hardwareAccelerated="true"
+      android:launchMode="singleTop"
+      android:name="io.flutter.embedding.android.FlutterActivity"
+      android:theme="@style/LaunchTheme"
+      android:windowSoftInputMode="adjustResize">
+      <intent-filter>
+        <action android:name="android.intent.action.MAIN"/>
+        <category android:name="android.intent.category.LAUNCHER"/>
+      </intent-filter>
+    </activity>
+  </application>
+
+  <!-- The INTERNET permission is required for development. Specifically,
+       flutter needs it to communicate with the running application
+       to allow setting breakpoints, to provide hot reload, etc.
+  -->
+  <uses-permission android:name="android.permission.INTERNET"/>
+</manifest>

+ 20 - 0
example/android/app/src/main/java/io/flutter/plugins/webviewflutterexample/EmbeddingV1Activity.java

@@ -0,0 +1,20 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+package io.flutter.plugins.webviewflutterexample;
+
+import android.os.Bundle;
+import dev.flutter.plugins.e2e.E2EPlugin;
+import io.flutter.app.FlutterActivity;
+import io.flutter.plugins.webviewflutter.WebViewFlutterPlugin;
+
+public class EmbeddingV1Activity extends FlutterActivity {
+  @Override
+  protected void onCreate(Bundle savedInstanceState) {
+    super.onCreate(savedInstanceState);
+    E2EPlugin.registerWith(registrarFor("dev.flutter.plugins.e2e.E2EPlugin"));
+    WebViewFlutterPlugin.registerWith(
+        registrarFor("io.flutter.plugins.webviewflutter.WebViewFlutterPlugin"));
+  }
+}

+ 12 - 0
example/android/app/src/main/res/drawable/launch_background.xml

@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Modify this file to customize your launch splash screen -->
+<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
+    <item android:drawable="@android:color/white" />
+
+    <!-- You can insert your own image assets here -->
+    <!-- <item>
+        <bitmap
+            android:gravity="center"
+            android:src="@mipmap/launch_image" />
+    </item> -->
+</layer-list>

BIN
example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png


BIN
example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png


BIN
example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png


BIN
example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png


BIN
example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png


+ 8 - 0
example/android/app/src/main/res/values/styles.xml

@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+    <style name="LaunchTheme" parent="@android:style/Theme.Black.NoTitleBar">
+        <!-- Show a splash screen on the activity. Automatically removed when
+             Flutter draws its first frame -->
+        <item name="android:windowBackground">@drawable/launch_background</item>
+    </style>
+</resources>

+ 29 - 0
example/android/build.gradle

@@ -0,0 +1,29 @@
+buildscript {
+    repositories {
+        google()
+        jcenter()
+    }
+
+    dependencies {
+        classpath 'com.android.tools.build:gradle:3.3.0'
+    }
+}
+
+allprojects {
+    repositories {
+        google()
+        jcenter()
+    }
+}
+
+rootProject.buildDir = '../build'
+subprojects {
+    project.buildDir = "${rootProject.buildDir}/${project.name}"
+}
+subprojects {
+    project.evaluationDependsOn(':app')
+}
+
+task clean(type: Delete) {
+    delete rootProject.buildDir
+}

+ 4 - 0
example/android/gradle.properties

@@ -0,0 +1,4 @@
+org.gradle.jvmargs=-Xmx1536M
+android.useAndroidX=true
+android.enableJetifier=true
+android.enableR8=true

+ 6 - 0
example/android/gradle/wrapper/gradle-wrapper.properties

@@ -0,0 +1,6 @@
+#Fri Jun 23 08:50:38 CEST 2017
+distributionBase=GRADLE_USER_HOME
+distributionPath=wrapper/dists
+zipStoreBase=GRADLE_USER_HOME
+zipStorePath=wrapper/dists
+distributionUrl=https\://services.gradle.org/distributions/gradle-4.10.2-all.zip

+ 15 - 0
example/android/settings.gradle

@@ -0,0 +1,15 @@
+include ':app'
+
+def flutterProjectRoot = rootProject.projectDir.parentFile.toPath()
+
+def plugins = new Properties()
+def pluginsFile = new File(flutterProjectRoot.toFile(), '.flutter-plugins')
+if (pluginsFile.exists()) {
+    pluginsFile.withReader('UTF-8') { reader -> plugins.load(reader) }
+}
+
+plugins.each { name, path ->
+    def pluginDirectory = flutterProjectRoot.resolve(path).resolve('android').toFile()
+    include ":$name"
+    project(":$name").projectDir = pluginDirectory
+}

BIN
example/assets/sample_audio.ogg


+ 26 - 0
example/ios/Flutter/AppFrameworkInfo.plist

@@ -0,0 +1,26 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+  <key>CFBundleDevelopmentRegion</key>
+  <string>en</string>
+  <key>CFBundleExecutable</key>
+  <string>App</string>
+  <key>CFBundleIdentifier</key>
+  <string>io.flutter.flutter.app</string>
+  <key>CFBundleInfoDictionaryVersion</key>
+  <string>6.0</string>
+  <key>CFBundleName</key>
+  <string>App</string>
+  <key>CFBundlePackageType</key>
+  <string>FMWK</string>
+  <key>CFBundleShortVersionString</key>
+  <string>1.0</string>
+  <key>CFBundleSignature</key>
+  <string>????</string>
+  <key>CFBundleVersion</key>
+  <string>1.0</string>
+  <key>MinimumOSVersion</key>
+  <string>8.0</string>
+</dict>
+</plist>

+ 2 - 0
example/ios/Flutter/Debug.xcconfig

@@ -0,0 +1,2 @@
+#include "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"
+#include "Generated.xcconfig"

+ 2 - 0
example/ios/Flutter/Release.xcconfig

@@ -0,0 +1,2 @@
+#include "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"
+#include "Generated.xcconfig"

+ 625 - 0
example/ios/Runner.xcodeproj/project.pbxproj

@@ -0,0 +1,625 @@
+// !$*UTF8*$!
+{
+	archiveVersion = 1;
+	classes = {
+	};
+	objectVersion = 46;
+	objects = {
+
+/* Begin PBXBuildFile section */
+		1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; };
+		3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; };
+		3B80C3941E831B6300D905FE /* App.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 3B80C3931E831B6300D905FE /* App.framework */; };
+		3B80C3951E831B6300D905FE /* App.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 3B80C3931E831B6300D905FE /* App.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; };
+		68BDCAF623C3F97800D9C032 /* FLTWebViewTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 68BDCAF523C3F97800D9C032 /* FLTWebViewTests.m */; };
+		9705A1C61CF904A100538489 /* Flutter.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 9740EEBA1CF902C7004384FC /* Flutter.framework */; };
+		9705A1C71CF904A300538489 /* Flutter.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 9740EEBA1CF902C7004384FC /* Flutter.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; };
+		978B8F6F1D3862AE00F588F7 /* AppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 7AFFD8EE1D35381100E5BB4D /* AppDelegate.m */; };
+		97C146F31CF9000F007C117D /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 97C146F21CF9000F007C117D /* main.m */; };
+		97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; };
+		97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; };
+		97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; };
+		9D26F6F82D91F92CC095EBA9 /* libPods-Runner.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 8B845D8FBDE0AAD6BE1A0386 /* libPods-Runner.a */; };
+/* End PBXBuildFile section */
+
+/* Begin PBXContainerItemProxy section */
+		68BDCAEE23C3F7CB00D9C032 /* PBXContainerItemProxy */ = {
+			isa = PBXContainerItemProxy;
+			containerPortal = 97C146E61CF9000F007C117D /* Project object */;
+			proxyType = 1;
+			remoteGlobalIDString = 97C146ED1CF9000F007C117D;
+			remoteInfo = Runner;
+		};
+/* End PBXContainerItemProxy section */
+
+/* Begin PBXCopyFilesBuildPhase section */
+		9705A1C41CF9048500538489 /* Embed Frameworks */ = {
+			isa = PBXCopyFilesBuildPhase;
+			buildActionMask = 2147483647;
+			dstPath = "";
+			dstSubfolderSpec = 10;
+			files = (
+				3B80C3951E831B6300D905FE /* App.framework in Embed Frameworks */,
+				9705A1C71CF904A300538489 /* Flutter.framework in Embed Frameworks */,
+			);
+			name = "Embed Frameworks";
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+/* End PBXCopyFilesBuildPhase section */
+
+/* Begin PBXFileReference section */
+		127772EEA7782174BE0D74B5 /* Pods-Runner.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.debug.xcconfig"; path = "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"; sourceTree = "<group>"; };
+		1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = "<group>"; };
+		1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = "<group>"; };
+		3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = "<group>"; };
+		3B80C3931E831B6300D905FE /* App.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = App.framework; path = Flutter/App.framework; sourceTree = "<group>"; };
+		68BDCAE923C3F7CB00D9C032 /* webview_flutter_exampleTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = webview_flutter_exampleTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
+		68BDCAED23C3F7CB00D9C032 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
+		68BDCAF523C3F97800D9C032 /* FLTWebViewTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = FLTWebViewTests.m; path = ../../../ios/Tests/FLTWebViewTests.m; sourceTree = "<group>"; };
+		7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = "<group>"; };
+		7AFFD8ED1D35381100E5BB4D /* AppDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AppDelegate.h; sourceTree = "<group>"; };
+		7AFFD8EE1D35381100E5BB4D /* AppDelegate.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AppDelegate.m; sourceTree = "<group>"; };
+		8B845D8FBDE0AAD6BE1A0386 /* libPods-Runner.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libPods-Runner.a"; sourceTree = BUILT_PRODUCTS_DIR; };
+		9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Debug.xcconfig; path = Flutter/Debug.xcconfig; sourceTree = "<group>"; };
+		9740EEB31CF90195004384FC /* Generated.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Generated.xcconfig; path = Flutter/Generated.xcconfig; sourceTree = "<group>"; };
+		9740EEBA1CF902C7004384FC /* Flutter.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Flutter.framework; path = Flutter/Flutter.framework; sourceTree = "<group>"; };
+		97C146EE1CF9000F007C117D /* Runner.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Runner.app; sourceTree = BUILT_PRODUCTS_DIR; };
+		97C146F21CF9000F007C117D /* main.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = "<group>"; };
+		97C146FB1CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = "<group>"; };
+		97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
+		97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = "<group>"; };
+		97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
+		C475C484BD510DD9CB2E403C /* Pods-Runner.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.release.xcconfig"; path = "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"; sourceTree = "<group>"; };
+/* End PBXFileReference section */
+
+/* Begin PBXFrameworksBuildPhase section */
+		68BDCAE623C3F7CB00D9C032 /* Frameworks */ = {
+			isa = PBXFrameworksBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		97C146EB1CF9000F007C117D /* Frameworks */ = {
+			isa = PBXFrameworksBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				9705A1C61CF904A100538489 /* Flutter.framework in Frameworks */,
+				3B80C3941E831B6300D905FE /* App.framework in Frameworks */,
+				9D26F6F82D91F92CC095EBA9 /* libPods-Runner.a in Frameworks */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+/* End PBXFrameworksBuildPhase section */
+
+/* Begin PBXGroup section */
+		68BDCAEA23C3F7CB00D9C032 /* webview_flutter_exampleTests */ = {
+			isa = PBXGroup;
+			children = (
+				68BDCAF523C3F97800D9C032 /* FLTWebViewTests.m */,
+				68BDCAED23C3F7CB00D9C032 /* Info.plist */,
+			);
+			path = webview_flutter_exampleTests;
+			sourceTree = "<group>";
+		};
+		9740EEB11CF90186004384FC /* Flutter */ = {
+			isa = PBXGroup;
+			children = (
+				3B80C3931E831B6300D905FE /* App.framework */,
+				3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */,
+				9740EEBA1CF902C7004384FC /* Flutter.framework */,
+				9740EEB21CF90195004384FC /* Debug.xcconfig */,
+				7AFA3C8E1D35360C0083082E /* Release.xcconfig */,
+				9740EEB31CF90195004384FC /* Generated.xcconfig */,
+			);
+			name = Flutter;
+			sourceTree = "<group>";
+		};
+		97C146E51CF9000F007C117D = {
+			isa = PBXGroup;
+			children = (
+				9740EEB11CF90186004384FC /* Flutter */,
+				97C146F01CF9000F007C117D /* Runner */,
+				68BDCAEA23C3F7CB00D9C032 /* webview_flutter_exampleTests */,
+				97C146EF1CF9000F007C117D /* Products */,
+				C6FFB52F5C2B8A41A7E39DE2 /* Pods */,
+				B6736FC417BDCCDA377E779D /* Frameworks */,
+			);
+			sourceTree = "<group>";
+		};
+		97C146EF1CF9000F007C117D /* Products */ = {
+			isa = PBXGroup;
+			children = (
+				97C146EE1CF9000F007C117D /* Runner.app */,
+				68BDCAE923C3F7CB00D9C032 /* webview_flutter_exampleTests.xctest */,
+			);
+			name = Products;
+			sourceTree = "<group>";
+		};
+		97C146F01CF9000F007C117D /* Runner */ = {
+			isa = PBXGroup;
+			children = (
+				7AFFD8ED1D35381100E5BB4D /* AppDelegate.h */,
+				7AFFD8EE1D35381100E5BB4D /* AppDelegate.m */,
+				97C146FA1CF9000F007C117D /* Main.storyboard */,
+				97C146FD1CF9000F007C117D /* Assets.xcassets */,
+				97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */,
+				97C147021CF9000F007C117D /* Info.plist */,
+				97C146F11CF9000F007C117D /* Supporting Files */,
+				1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */,
+				1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */,
+			);
+			path = Runner;
+			sourceTree = "<group>";
+		};
+		97C146F11CF9000F007C117D /* Supporting Files */ = {
+			isa = PBXGroup;
+			children = (
+				97C146F21CF9000F007C117D /* main.m */,
+			);
+			name = "Supporting Files";
+			sourceTree = "<group>";
+		};
+		B6736FC417BDCCDA377E779D /* Frameworks */ = {
+			isa = PBXGroup;
+			children = (
+				8B845D8FBDE0AAD6BE1A0386 /* libPods-Runner.a */,
+			);
+			name = Frameworks;
+			sourceTree = "<group>";
+		};
+		C6FFB52F5C2B8A41A7E39DE2 /* Pods */ = {
+			isa = PBXGroup;
+			children = (
+				127772EEA7782174BE0D74B5 /* Pods-Runner.debug.xcconfig */,
+				C475C484BD510DD9CB2E403C /* Pods-Runner.release.xcconfig */,
+			);
+			name = Pods;
+			sourceTree = "<group>";
+		};
+/* End PBXGroup section */
+
+/* Begin PBXNativeTarget section */
+		68BDCAE823C3F7CB00D9C032 /* webview_flutter_exampleTests */ = {
+			isa = PBXNativeTarget;
+			buildConfigurationList = 68BDCAF223C3F7CB00D9C032 /* Build configuration list for PBXNativeTarget "webview_flutter_exampleTests" */;
+			buildPhases = (
+				68BDCAE523C3F7CB00D9C032 /* Sources */,
+				68BDCAE623C3F7CB00D9C032 /* Frameworks */,
+				68BDCAE723C3F7CB00D9C032 /* Resources */,
+			);
+			buildRules = (
+			);
+			dependencies = (
+				68BDCAEF23C3F7CB00D9C032 /* PBXTargetDependency */,
+			);
+			name = webview_flutter_exampleTests;
+			productName = webview_flutter_exampleTests;
+			productReference = 68BDCAE923C3F7CB00D9C032 /* webview_flutter_exampleTests.xctest */;
+			productType = "com.apple.product-type.bundle.unit-test";
+		};
+		97C146ED1CF9000F007C117D /* Runner */ = {
+			isa = PBXNativeTarget;
+			buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */;
+			buildPhases = (
+				B71376B4FB8384EF9D5F3F84 /* [CP] Check Pods Manifest.lock */,
+				9740EEB61CF901F6004384FC /* Run Script */,
+				97C146EA1CF9000F007C117D /* Sources */,
+				97C146EB1CF9000F007C117D /* Frameworks */,
+				97C146EC1CF9000F007C117D /* Resources */,
+				9705A1C41CF9048500538489 /* Embed Frameworks */,
+				3B06AD1E1E4923F5004D2608 /* Thin Binary */,
+				A1F14D6FD37A3C5047F5A5AD /* [CP] Embed Pods Frameworks */,
+			);
+			buildRules = (
+			);
+			dependencies = (
+			);
+			name = Runner;
+			productName = Runner;
+			productReference = 97C146EE1CF9000F007C117D /* Runner.app */;
+			productType = "com.apple.product-type.application";
+		};
+/* End PBXNativeTarget section */
+
+/* Begin PBXProject section */
+		97C146E61CF9000F007C117D /* Project object */ = {
+			isa = PBXProject;
+			attributes = {
+				DefaultBuildSystemTypeForWorkspace = Original;
+				LastUpgradeCheck = 1030;
+				ORGANIZATIONNAME = "The Chromium Authors";
+				TargetAttributes = {
+					97C146ED1CF9000F007C117D = {
+						CreatedOnToolsVersion = 7.3.1;
+					};
+				};
+			};
+			buildConfigurationList = 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */;
+			compatibilityVersion = "Xcode 3.2";
+			developmentRegion = en;
+			hasScannedForEncodings = 0;
+			knownRegions = (
+				en,
+				Base,
+			);
+			mainGroup = 97C146E51CF9000F007C117D;
+			productRefGroup = 97C146EF1CF9000F007C117D /* Products */;
+			projectDirPath = "";
+			projectRoot = "";
+			targets = (
+				97C146ED1CF9000F007C117D /* Runner */,
+				68BDCAE823C3F7CB00D9C032 /* webview_flutter_exampleTests */,
+			);
+		};
+/* End PBXProject section */
+
+/* Begin PBXResourcesBuildPhase section */
+		68BDCAE723C3F7CB00D9C032 /* Resources */ = {
+			isa = PBXResourcesBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		97C146EC1CF9000F007C117D /* Resources */ = {
+			isa = PBXResourcesBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */,
+				3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */,
+				97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */,
+				97C146FC1CF9000F007C117D /* Main.storyboard in Resources */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+/* End PBXResourcesBuildPhase section */
+
+/* Begin PBXShellScriptBuildPhase section */
+		3B06AD1E1E4923F5004D2608 /* Thin Binary */ = {
+			isa = PBXShellScriptBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+			);
+			inputPaths = (
+			);
+			name = "Thin Binary";
+			outputPaths = (
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+			shellPath = /bin/sh;
+			shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" thin";
+		};
+		9740EEB61CF901F6004384FC /* Run Script */ = {
+			isa = PBXShellScriptBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+			);
+			inputPaths = (
+			);
+			name = "Run Script";
+			outputPaths = (
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+			shellPath = /bin/sh;
+			shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" build";
+		};
+		A1F14D6FD37A3C5047F5A5AD /* [CP] Embed Pods Frameworks */ = {
+			isa = PBXShellScriptBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+			);
+			inputPaths = (
+			);
+			name = "[CP] Embed Pods Frameworks";
+			outputPaths = (
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+			shellPath = /bin/sh;
+			shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks.sh\"\n";
+			showEnvVarsInLog = 0;
+		};
+		B71376B4FB8384EF9D5F3F84 /* [CP] Check Pods Manifest.lock */ = {
+			isa = PBXShellScriptBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+			);
+			inputPaths = (
+				"${PODS_PODFILE_DIR_PATH}/Podfile.lock",
+				"${PODS_ROOT}/Manifest.lock",
+			);
+			name = "[CP] Check Pods Manifest.lock";
+			outputPaths = (
+				"$(DERIVED_FILE_DIR)/Pods-Runner-checkManifestLockResult.txt",
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+			shellPath = /bin/sh;
+			shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n    # print error to STDERR\n    echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n    exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n";
+			showEnvVarsInLog = 0;
+		};
+/* End PBXShellScriptBuildPhase section */
+
+/* Begin PBXSourcesBuildPhase section */
+		68BDCAE523C3F7CB00D9C032 /* Sources */ = {
+			isa = PBXSourcesBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				68BDCAF623C3F97800D9C032 /* FLTWebViewTests.m in Sources */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+		97C146EA1CF9000F007C117D /* Sources */ = {
+			isa = PBXSourcesBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				978B8F6F1D3862AE00F588F7 /* AppDelegate.m in Sources */,
+				97C146F31CF9000F007C117D /* main.m in Sources */,
+				1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
+/* End PBXSourcesBuildPhase section */
+
+/* Begin PBXTargetDependency section */
+		68BDCAEF23C3F7CB00D9C032 /* PBXTargetDependency */ = {
+			isa = PBXTargetDependency;
+			target = 97C146ED1CF9000F007C117D /* Runner */;
+			targetProxy = 68BDCAEE23C3F7CB00D9C032 /* PBXContainerItemProxy */;
+		};
+/* End PBXTargetDependency section */
+
+/* Begin PBXVariantGroup section */
+		97C146FA1CF9000F007C117D /* Main.storyboard */ = {
+			isa = PBXVariantGroup;
+			children = (
+				97C146FB1CF9000F007C117D /* Base */,
+			);
+			name = Main.storyboard;
+			sourceTree = "<group>";
+		};
+		97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */ = {
+			isa = PBXVariantGroup;
+			children = (
+				97C147001CF9000F007C117D /* Base */,
+			);
+			name = LaunchScreen.storyboard;
+			sourceTree = "<group>";
+		};
+/* End PBXVariantGroup section */
+
+/* Begin XCBuildConfiguration section */
+		68BDCAF023C3F7CB00D9C032 /* Debug */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				BUNDLE_LOADER = "$(TEST_HOST)";
+				CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
+				CLANG_CXX_LANGUAGE_STANDARD = "gnu++14";
+				CLANG_ENABLE_OBJC_WEAK = YES;
+				CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
+				CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
+				CODE_SIGN_STYLE = Automatic;
+				GCC_C_LANGUAGE_STANDARD = gnu11;
+				INFOPLIST_FILE = webview_flutter_exampleTests/Info.plist;
+				IPHONEOS_DEPLOYMENT_TARGET = 13.2;
+				LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
+				MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
+				MTL_FAST_MATH = YES;
+				PRODUCT_BUNDLE_IDENTIFIER = "com.google.webview-flutter-exampleTests";
+				PRODUCT_NAME = "$(TARGET_NAME)";
+				TARGETED_DEVICE_FAMILY = "1,2";
+				TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/Runner";
+			};
+			name = Debug;
+		};
+		68BDCAF123C3F7CB00D9C032 /* Release */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				BUNDLE_LOADER = "$(TEST_HOST)";
+				CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
+				CLANG_CXX_LANGUAGE_STANDARD = "gnu++14";
+				CLANG_ENABLE_OBJC_WEAK = YES;
+				CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
+				CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
+				CODE_SIGN_STYLE = Automatic;
+				GCC_C_LANGUAGE_STANDARD = gnu11;
+				INFOPLIST_FILE = webview_flutter_exampleTests/Info.plist;
+				IPHONEOS_DEPLOYMENT_TARGET = 13.2;
+				LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
+				MTL_FAST_MATH = YES;
+				PRODUCT_BUNDLE_IDENTIFIER = "com.google.webview-flutter-exampleTests";
+				PRODUCT_NAME = "$(TARGET_NAME)";
+				TARGETED_DEVICE_FAMILY = "1,2";
+				TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/Runner";
+			};
+			name = Release;
+		};
+		97C147031CF9000F007C117D /* Debug */ = {
+			isa = XCBuildConfiguration;
+			baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */;
+			buildSettings = {
+				ALWAYS_SEARCH_USER_PATHS = NO;
+				CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES;
+				CLANG_ANALYZER_NONNULL = YES;
+				CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
+				CLANG_CXX_LIBRARY = "libc++";
+				CLANG_ENABLE_MODULES = YES;
+				CLANG_ENABLE_OBJC_ARC = YES;
+				CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
+				CLANG_WARN_BOOL_CONVERSION = YES;
+				CLANG_WARN_COMMA = YES;
+				CLANG_WARN_CONSTANT_CONVERSION = YES;
+				CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
+				CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
+				CLANG_WARN_EMPTY_BODY = YES;
+				CLANG_WARN_ENUM_CONVERSION = YES;
+				CLANG_WARN_INFINITE_RECURSION = YES;
+				CLANG_WARN_INT_CONVERSION = YES;
+				CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
+				CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
+				CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
+				CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
+				CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
+				CLANG_WARN_STRICT_PROTOTYPES = YES;
+				CLANG_WARN_SUSPICIOUS_MOVE = YES;
+				CLANG_WARN_UNREACHABLE_CODE = YES;
+				CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
+				"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
+				COPY_PHASE_STRIP = NO;
+				DEBUG_INFORMATION_FORMAT = dwarf;
+				ENABLE_STRICT_OBJC_MSGSEND = YES;
+				ENABLE_TESTABILITY = YES;
+				GCC_C_LANGUAGE_STANDARD = gnu99;
+				GCC_DYNAMIC_NO_PIC = NO;
+				GCC_NO_COMMON_BLOCKS = YES;
+				GCC_OPTIMIZATION_LEVEL = 0;
+				GCC_PREPROCESSOR_DEFINITIONS = (
+					"DEBUG=1",
+					"$(inherited)",
+				);
+				GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
+				GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
+				GCC_WARN_UNDECLARED_SELECTOR = YES;
+				GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
+				GCC_WARN_UNUSED_FUNCTION = YES;
+				GCC_WARN_UNUSED_VARIABLE = YES;
+				IPHONEOS_DEPLOYMENT_TARGET = 8.0;
+				MTL_ENABLE_DEBUG_INFO = YES;
+				ONLY_ACTIVE_ARCH = YES;
+				SDKROOT = iphoneos;
+				TARGETED_DEVICE_FAMILY = "1,2";
+			};
+			name = Debug;
+		};
+		97C147041CF9000F007C117D /* Release */ = {
+			isa = XCBuildConfiguration;
+			baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */;
+			buildSettings = {
+				ALWAYS_SEARCH_USER_PATHS = NO;
+				CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES;
+				CLANG_ANALYZER_NONNULL = YES;
+				CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
+				CLANG_CXX_LIBRARY = "libc++";
+				CLANG_ENABLE_MODULES = YES;
+				CLANG_ENABLE_OBJC_ARC = YES;
+				CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
+				CLANG_WARN_BOOL_CONVERSION = YES;
+				CLANG_WARN_COMMA = YES;
+				CLANG_WARN_CONSTANT_CONVERSION = YES;
+				CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
+				CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
+				CLANG_WARN_EMPTY_BODY = YES;
+				CLANG_WARN_ENUM_CONVERSION = YES;
+				CLANG_WARN_INFINITE_RECURSION = YES;
+				CLANG_WARN_INT_CONVERSION = YES;
+				CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
+				CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
+				CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
+				CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
+				CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
+				CLANG_WARN_STRICT_PROTOTYPES = YES;
+				CLANG_WARN_SUSPICIOUS_MOVE = YES;
+				CLANG_WARN_UNREACHABLE_CODE = YES;
+				CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
+				"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
+				COPY_PHASE_STRIP = NO;
+				DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
+				ENABLE_NS_ASSERTIONS = NO;
+				ENABLE_STRICT_OBJC_MSGSEND = YES;
+				GCC_C_LANGUAGE_STANDARD = gnu99;
+				GCC_NO_COMMON_BLOCKS = YES;
+				GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
+				GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
+				GCC_WARN_UNDECLARED_SELECTOR = YES;
+				GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
+				GCC_WARN_UNUSED_FUNCTION = YES;
+				GCC_WARN_UNUSED_VARIABLE = YES;
+				IPHONEOS_DEPLOYMENT_TARGET = 8.0;
+				MTL_ENABLE_DEBUG_INFO = NO;
+				SDKROOT = iphoneos;
+				TARGETED_DEVICE_FAMILY = "1,2";
+				VALIDATE_PRODUCT = YES;
+			};
+			name = Release;
+		};
+		97C147061CF9000F007C117D /* Debug */ = {
+			isa = XCBuildConfiguration;
+			baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */;
+			buildSettings = {
+				ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
+				CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)";
+				DEVELOPMENT_TEAM = "";
+				ENABLE_BITCODE = NO;
+				FRAMEWORK_SEARCH_PATHS = (
+					"$(inherited)",
+					"$(PROJECT_DIR)/Flutter",
+				);
+				INFOPLIST_FILE = Runner/Info.plist;
+				LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
+				LIBRARY_SEARCH_PATHS = (
+					"$(inherited)",
+					"$(PROJECT_DIR)/Flutter",
+				);
+				PRODUCT_BUNDLE_IDENTIFIER = io.flutter.plugins.webviewFlutterExample;
+				PRODUCT_NAME = "$(TARGET_NAME)";
+				VERSIONING_SYSTEM = "apple-generic";
+			};
+			name = Debug;
+		};
+		97C147071CF9000F007C117D /* Release */ = {
+			isa = XCBuildConfiguration;
+			baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */;
+			buildSettings = {
+				ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
+				CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)";
+				DEVELOPMENT_TEAM = "";
+				ENABLE_BITCODE = NO;
+				FRAMEWORK_SEARCH_PATHS = (
+					"$(inherited)",
+					"$(PROJECT_DIR)/Flutter",
+				);
+				INFOPLIST_FILE = Runner/Info.plist;
+				LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
+				LIBRARY_SEARCH_PATHS = (
+					"$(inherited)",
+					"$(PROJECT_DIR)/Flutter",
+				);
+				PRODUCT_BUNDLE_IDENTIFIER = io.flutter.plugins.webviewFlutterExample;
+				PRODUCT_NAME = "$(TARGET_NAME)";
+				VERSIONING_SYSTEM = "apple-generic";
+			};
+			name = Release;
+		};
+/* End XCBuildConfiguration section */
+
+/* Begin XCConfigurationList section */
+		68BDCAF223C3F7CB00D9C032 /* Build configuration list for PBXNativeTarget "webview_flutter_exampleTests" */ = {
+			isa = XCConfigurationList;
+			buildConfigurations = (
+				68BDCAF023C3F7CB00D9C032 /* Debug */,
+				68BDCAF123C3F7CB00D9C032 /* Release */,
+			);
+			defaultConfigurationIsVisible = 0;
+			defaultConfigurationName = Release;
+		};
+		97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */ = {
+			isa = XCConfigurationList;
+			buildConfigurations = (
+				97C147031CF9000F007C117D /* Debug */,
+				97C147041CF9000F007C117D /* Release */,
+			);
+			defaultConfigurationIsVisible = 0;
+			defaultConfigurationName = Release;
+		};
+		97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */ = {
+			isa = XCConfigurationList;
+			buildConfigurations = (
+				97C147061CF9000F007C117D /* Debug */,
+				97C147071CF9000F007C117D /* Release */,
+			);
+			defaultConfigurationIsVisible = 0;
+			defaultConfigurationName = Release;
+		};
+/* End XCConfigurationList section */
+	};
+	rootObject = 97C146E61CF9000F007C117D /* Project object */;
+}

+ 7 - 0
example/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata

@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<Workspace
+   version = "1.0">
+   <FileRef
+      location = "group:Runner.xcodeproj">
+   </FileRef>
+</Workspace>

+ 97 - 0
example/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme

@@ -0,0 +1,97 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<Scheme
+   LastUpgradeVersion = "1030"
+   version = "1.3">
+   <BuildAction
+      parallelizeBuildables = "YES"
+      buildImplicitDependencies = "YES">
+      <BuildActionEntries>
+         <BuildActionEntry
+            buildForTesting = "YES"
+            buildForRunning = "YES"
+            buildForProfiling = "YES"
+            buildForArchiving = "YES"
+            buildForAnalyzing = "YES">
+            <BuildableReference
+               BuildableIdentifier = "primary"
+               BlueprintIdentifier = "97C146ED1CF9000F007C117D"
+               BuildableName = "Runner.app"
+               BlueprintName = "Runner"
+               ReferencedContainer = "container:Runner.xcodeproj">
+            </BuildableReference>
+         </BuildActionEntry>
+      </BuildActionEntries>
+   </BuildAction>
+   <TestAction
+      buildConfiguration = "Debug"
+      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
+      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
+      shouldUseLaunchSchemeArgsEnv = "YES">
+      <MacroExpansion>
+         <BuildableReference
+            BuildableIdentifier = "primary"
+            BlueprintIdentifier = "97C146ED1CF9000F007C117D"
+            BuildableName = "Runner.app"
+            BlueprintName = "Runner"
+            ReferencedContainer = "container:Runner.xcodeproj">
+         </BuildableReference>
+      </MacroExpansion>
+      <Testables>
+         <TestableReference
+            skipped = "NO">
+            <BuildableReference
+               BuildableIdentifier = "primary"
+               BlueprintIdentifier = "68BDCAE823C3F7CB00D9C032"
+               BuildableName = "webview_flutter_exampleTests.xctest"
+               BlueprintName = "webview_flutter_exampleTests"
+               ReferencedContainer = "container:Runner.xcodeproj">
+            </BuildableReference>
+         </TestableReference>
+      </Testables>
+   </TestAction>
+   <LaunchAction
+      buildConfiguration = "Debug"
+      selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
+      selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
+      launchStyle = "0"
+      useCustomWorkingDirectory = "NO"
+      ignoresPersistentStateOnLaunch = "NO"
+      debugDocumentVersioning = "YES"
+      debugServiceExtension = "internal"
+      allowLocationSimulation = "YES">
+      <BuildableProductRunnable
+         runnableDebuggingMode = "0">
+         <BuildableReference
+            BuildableIdentifier = "primary"
+            BlueprintIdentifier = "97C146ED1CF9000F007C117D"
+            BuildableName = "Runner.app"
+            BlueprintName = "Runner"
+            ReferencedContainer = "container:Runner.xcodeproj">
+         </BuildableReference>
+      </BuildableProductRunnable>
+   </LaunchAction>
+   <ProfileAction
+      buildConfiguration = "Release"
+      shouldUseLaunchSchemeArgsEnv = "YES"
+      savedToolIdentifier = ""
+      useCustomWorkingDirectory = "NO"
+      debugDocumentVersioning = "YES">
+      <BuildableProductRunnable
+         runnableDebuggingMode = "0">
+         <BuildableReference
+            BuildableIdentifier = "primary"
+            BlueprintIdentifier = "97C146ED1CF9000F007C117D"
+            BuildableName = "Runner.app"
+            BlueprintName = "Runner"
+            ReferencedContainer = "container:Runner.xcodeproj">
+         </BuildableReference>
+      </BuildableProductRunnable>
+   </ProfileAction>
+   <AnalyzeAction
+      buildConfiguration = "Debug">
+   </AnalyzeAction>
+   <ArchiveAction
+      buildConfiguration = "Release"
+      revealArchiveInOrganizer = "YES">
+   </ArchiveAction>
+</Scheme>

+ 10 - 0
example/ios/Runner.xcworkspace/contents.xcworkspacedata

@@ -0,0 +1,10 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<Workspace
+   version = "1.0">
+   <FileRef
+      location = "group:Runner.xcodeproj">
+   </FileRef>
+   <FileRef
+      location = "group:Pods/Pods.xcodeproj">
+   </FileRef>
+</Workspace>

+ 8 - 0
example/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist

@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+	<key>IDEDidComputeMac32BitWarning</key>
+	<true/>
+</dict>
+</plist>

+ 10 - 0
example/ios/Runner/AppDelegate.h

@@ -0,0 +1,10 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#import <Flutter/Flutter.h>
+#import <UIKit/UIKit.h>
+
+@interface AppDelegate : FlutterAppDelegate
+
+@end

+ 17 - 0
example/ios/Runner/AppDelegate.m

@@ -0,0 +1,17 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "AppDelegate.h"
+#include "GeneratedPluginRegistrant.h"
+
+@implementation AppDelegate
+
+- (BOOL)application:(UIApplication *)application
+    didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
+  [GeneratedPluginRegistrant registerWithRegistry:self];
+  // Override point for customization after application launch.
+  return [super application:application didFinishLaunchingWithOptions:launchOptions];
+}
+
+@end

+ 122 - 0
example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json

@@ -0,0 +1,122 @@
+{
+  "images" : [
+    {
+      "size" : "20x20",
+      "idiom" : "iphone",
+      "filename" : "Icon-App-20x20@2x.png",
+      "scale" : "2x"
+    },
+    {
+      "size" : "20x20",
+      "idiom" : "iphone",
+      "filename" : "Icon-App-20x20@3x.png",
+      "scale" : "3x"
+    },
+    {
+      "size" : "29x29",
+      "idiom" : "iphone",
+      "filename" : "Icon-App-29x29@1x.png",
+      "scale" : "1x"
+    },
+    {
+      "size" : "29x29",
+      "idiom" : "iphone",
+      "filename" : "Icon-App-29x29@2x.png",
+      "scale" : "2x"
+    },
+    {
+      "size" : "29x29",
+      "idiom" : "iphone",
+      "filename" : "Icon-App-29x29@3x.png",
+      "scale" : "3x"
+    },
+    {
+      "size" : "40x40",
+      "idiom" : "iphone",
+      "filename" : "Icon-App-40x40@2x.png",
+      "scale" : "2x"
+    },
+    {
+      "size" : "40x40",
+      "idiom" : "iphone",
+      "filename" : "Icon-App-40x40@3x.png",
+      "scale" : "3x"
+    },
+    {
+      "size" : "60x60",
+      "idiom" : "iphone",
+      "filename" : "Icon-App-60x60@2x.png",
+      "scale" : "2x"
+    },
+    {
+      "size" : "60x60",
+      "idiom" : "iphone",
+      "filename" : "Icon-App-60x60@3x.png",
+      "scale" : "3x"
+    },
+    {
+      "size" : "20x20",
+      "idiom" : "ipad",
+      "filename" : "Icon-App-20x20@1x.png",
+      "scale" : "1x"
+    },
+    {
+      "size" : "20x20",
+      "idiom" : "ipad",
+      "filename" : "Icon-App-20x20@2x.png",
+      "scale" : "2x"
+    },
+    {
+      "size" : "29x29",
+      "idiom" : "ipad",
+      "filename" : "Icon-App-29x29@1x.png",
+      "scale" : "1x"
+    },
+    {
+      "size" : "29x29",
+      "idiom" : "ipad",
+      "filename" : "Icon-App-29x29@2x.png",
+      "scale" : "2x"
+    },
+    {
+      "size" : "40x40",
+      "idiom" : "ipad",
+      "filename" : "Icon-App-40x40@1x.png",
+      "scale" : "1x"
+    },
+    {
+      "size" : "40x40",
+      "idiom" : "ipad",
+      "filename" : "Icon-App-40x40@2x.png",
+      "scale" : "2x"
+    },
+    {
+      "size" : "76x76",
+      "idiom" : "ipad",
+      "filename" : "Icon-App-76x76@1x.png",
+      "scale" : "1x"
+    },
+    {
+      "size" : "76x76",
+      "idiom" : "ipad",
+      "filename" : "Icon-App-76x76@2x.png",
+      "scale" : "2x"
+    },
+    {
+      "size" : "83.5x83.5",
+      "idiom" : "ipad",
+      "filename" : "Icon-App-83.5x83.5@2x.png",
+      "scale" : "2x"
+    },
+    {
+      "size" : "1024x1024",
+      "idiom" : "ios-marketing",
+      "filename" : "Icon-App-1024x1024@1x.png",
+      "scale" : "1x"
+    }
+  ],
+  "info" : {
+    "version" : 1,
+    "author" : "xcode"
+  }
+}

BIN
example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png


BIN
example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png


BIN
example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png


BIN
example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png


BIN
example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png


BIN
example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png


BIN
example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png


BIN
example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png


BIN
example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png


BIN
example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png


BIN
example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png


BIN
example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png


BIN
example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png


BIN
example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png


BIN
example/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png


+ 23 - 0
example/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json

@@ -0,0 +1,23 @@
+{
+  "images" : [
+    {
+      "idiom" : "universal",
+      "filename" : "LaunchImage.png",
+      "scale" : "1x"
+    },
+    {
+      "idiom" : "universal",
+      "filename" : "LaunchImage@2x.png",
+      "scale" : "2x"
+    },
+    {
+      "idiom" : "universal",
+      "filename" : "LaunchImage@3x.png",
+      "scale" : "3x"
+    }
+  ],
+  "info" : {
+    "version" : 1,
+    "author" : "xcode"
+  }
+}

BIN
example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png


BIN
example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png


BIN
example/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png


+ 5 - 0
example/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md

@@ -0,0 +1,5 @@
+# Launch Screen Assets
+
+You can customize the launch screen with your own desired assets by replacing the image files in this directory.
+
+You can also do it by opening your Flutter project's Xcode project with `open ios/Runner.xcworkspace`, selecting `Runner/Assets.xcassets` in the Project Navigator and dropping in the desired images.

+ 37 - 0
example/ios/Runner/Base.lproj/LaunchScreen.storyboard

@@ -0,0 +1,37 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="12121" systemVersion="16G29" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" colorMatched="YES" initialViewController="01J-lp-oVM">
+    <dependencies>
+        <deployment identifier="iOS"/>
+        <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="12089"/>
+    </dependencies>
+    <scenes>
+        <!--View Controller-->
+        <scene sceneID="EHf-IW-A2E">
+            <objects>
+                <viewController id="01J-lp-oVM" sceneMemberID="viewController">
+                    <layoutGuides>
+                        <viewControllerLayoutGuide type="top" id="Ydg-fD-yQy"/>
+                        <viewControllerLayoutGuide type="bottom" id="xbc-2k-c8Z"/>
+                    </layoutGuides>
+                    <view key="view" contentMode="scaleToFill" id="Ze5-6b-2t3">
+                        <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
+                        <subviews>
+                            <imageView opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" image="LaunchImage" translatesAutoresizingMaskIntoConstraints="NO" id="YRO-k0-Ey4">
+                            </imageView>
+                        </subviews>
+                        <color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
+                        <constraints>
+                            <constraint firstItem="YRO-k0-Ey4" firstAttribute="centerX" secondItem="Ze5-6b-2t3" secondAttribute="centerX" id="1a2-6s-vTC"/>
+                            <constraint firstItem="YRO-k0-Ey4" firstAttribute="centerY" secondItem="Ze5-6b-2t3" secondAttribute="centerY" id="4X2-HB-R7a"/>
+                        </constraints>
+                    </view>
+                </viewController>
+                <placeholder placeholderIdentifier="IBFirstResponder" id="iYj-Kq-Ea1" userLabel="First Responder" sceneMemberID="firstResponder"/>
+            </objects>
+            <point key="canvasLocation" x="53" y="375"/>
+        </scene>
+    </scenes>
+    <resources>
+        <image name="LaunchImage" width="168" height="185"/>
+    </resources>
+</document>

+ 26 - 0
example/ios/Runner/Base.lproj/Main.storyboard

@@ -0,0 +1,26 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="10117" systemVersion="15F34" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" initialViewController="BYZ-38-t0r">
+    <dependencies>
+        <deployment identifier="iOS"/>
+        <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="10085"/>
+    </dependencies>
+    <scenes>
+        <!--Flutter View Controller-->
+        <scene sceneID="tne-QT-ifu">
+            <objects>
+                <viewController id="BYZ-38-t0r" customClass="FlutterViewController" sceneMemberID="viewController">
+                    <layoutGuides>
+                        <viewControllerLayoutGuide type="top" id="y3c-jy-aDJ"/>
+                        <viewControllerLayoutGuide type="bottom" id="wfy-db-euE"/>
+                    </layoutGuides>
+                    <view key="view" contentMode="scaleToFill" id="8bC-Xf-vdC">
+                        <rect key="frame" x="0.0" y="0.0" width="600" height="600"/>
+                        <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
+                        <color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="calibratedWhite"/>
+                    </view>
+                </viewController>
+                <placeholder placeholderIdentifier="IBFirstResponder" id="dkx-z0-nzr" sceneMemberID="firstResponder"/>
+            </objects>
+        </scene>
+    </scenes>
+</document>

+ 47 - 0
example/ios/Runner/Info.plist

@@ -0,0 +1,47 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+	<key>CFBundleDevelopmentRegion</key>
+	<string>en</string>
+	<key>CFBundleExecutable</key>
+	<string>$(EXECUTABLE_NAME)</string>
+	<key>CFBundleIdentifier</key>
+	<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
+	<key>CFBundleInfoDictionaryVersion</key>
+	<string>6.0</string>
+	<key>CFBundleName</key>
+	<string>webview_flutter_example</string>
+	<key>CFBundlePackageType</key>
+	<string>APPL</string>
+	<key>CFBundleShortVersionString</key>
+	<string>$(FLUTTER_BUILD_NAME)</string>
+	<key>CFBundleSignature</key>
+	<string>????</string>
+	<key>CFBundleVersion</key>
+	<string>$(FLUTTER_BUILD_NUMBER)</string>
+	<key>LSRequiresIPhoneOS</key>
+	<true/>
+	<key>UILaunchStoryboardName</key>
+	<string>LaunchScreen</string>
+	<key>UIMainStoryboardFile</key>
+	<string>Main</string>
+	<key>UISupportedInterfaceOrientations</key>
+	<array>
+		<string>UIInterfaceOrientationPortrait</string>
+		<string>UIInterfaceOrientationLandscapeLeft</string>
+		<string>UIInterfaceOrientationLandscapeRight</string>
+	</array>
+	<key>UISupportedInterfaceOrientations~ipad</key>
+	<array>
+		<string>UIInterfaceOrientationPortrait</string>
+		<string>UIInterfaceOrientationPortraitUpsideDown</string>
+		<string>UIInterfaceOrientationLandscapeLeft</string>
+		<string>UIInterfaceOrientationLandscapeRight</string>
+	</array>
+	<key>io.flutter.embedded_views_preview</key>
+	<true/>
+	<key>UIViewControllerBasedStatusBarAppearance</key>
+	<false/>
+</dict>
+</plist>

+ 13 - 0
example/ios/Runner/main.m

@@ -0,0 +1,13 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#import <Flutter/Flutter.h>
+#import <UIKit/UIKit.h>
+#import "AppDelegate.h"
+
+int main(int argc, char* argv[]) {
+  @autoreleasepool {
+    return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
+  }
+}

+ 22 - 0
example/ios/webview_flutter_exampleTests/Info.plist

@@ -0,0 +1,22 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+	<key>CFBundleDevelopmentRegion</key>
+	<string>$(DEVELOPMENT_LANGUAGE)</string>
+	<key>CFBundleExecutable</key>
+	<string>$(EXECUTABLE_NAME)</string>
+	<key>CFBundleIdentifier</key>
+	<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
+	<key>CFBundleInfoDictionaryVersion</key>
+	<string>6.0</string>
+	<key>CFBundleName</key>
+	<string>$(PRODUCT_NAME)</string>
+	<key>CFBundlePackageType</key>
+	<string>$(PRODUCT_BUNDLE_PACKAGE_TYPE)</string>
+	<key>CFBundleShortVersionString</key>
+	<string>1.0</string>
+	<key>CFBundleVersion</key>
+	<string>1</string>
+</dict>
+</plist>

+ 338 - 0
example/lib/main.dart

@@ -0,0 +1,338 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+// ignore_for_file: public_member_api_docs
+
+import 'dart:async';
+import 'dart:convert';
+import 'package:flutter/material.dart';
+import 'package:webview_flutter/webview_flutter.dart';
+
+void main() => runApp(MaterialApp(home: WebViewExample()));
+
+const String kNavigationExamplePage = '''
+<!DOCTYPE html><html>
+<head><title>Navigation Delegate Example</title></head>
+<body>
+<p>
+The navigation delegate is set to block navigation to the youtube website.
+</p>
+<ul>
+<ul><a href="https://www.youtube.com/">https://www.youtube.com/</a></ul>
+<ul><a href="https://www.google.com/">https://www.google.com/</a></ul>
+</ul>
+</body>
+</html>
+''';
+
+class WebViewExample extends StatefulWidget {
+  @override
+  _WebViewExampleState createState() => _WebViewExampleState();
+}
+
+class _WebViewExampleState extends State<WebViewExample> {
+  final Completer<WebViewController> _controller =
+      Completer<WebViewController>();
+
+  @override
+  Widget build(BuildContext context) {
+    return Scaffold(
+      appBar: AppBar(
+        title: const Text('Flutter WebView example'),
+        // This drop down menu demonstrates that Flutter widgets can be shown over the web view.
+        actions: <Widget>[
+          NavigationControls(_controller.future),
+          SampleMenu(_controller.future),
+        ],
+      ),
+      // We're using a Builder here so we have a context that is below the Scaffold
+      // to allow calling Scaffold.of(context) so we can show a snackbar.
+      body: Builder(builder: (BuildContext context) {
+        return WebView(
+          initialUrl: 'https://flutter.dev',
+          javascriptMode: JavascriptMode.unrestricted,
+          onWebViewCreated: (WebViewController webViewController) {
+            _controller.complete(webViewController);
+          },
+          // TODO(iskakaushik): Remove this when collection literals makes it to stable.
+          // ignore: prefer_collection_literals
+          javascriptChannels: <JavascriptChannel>[
+            _toasterJavascriptChannel(context),
+          ].toSet(),
+          navigationDelegate: (NavigationRequest request) {
+            if (request.url.startsWith('https://www.youtube.com/')) {
+              print('blocking navigation to $request}');
+              return NavigationDecision.prevent;
+            }
+            print('allowing navigation to $request');
+            return NavigationDecision.navigate;
+          },
+          onPageStarted: (String url) {
+            print('Page started loading: $url');
+          },
+          onPageFinished: (String url) {
+            print('Page finished loading: $url');
+          },
+          gestureNavigationEnabled: true,
+        );
+      }),
+      floatingActionButton: favoriteButton(),
+    );
+  }
+
+  JavascriptChannel _toasterJavascriptChannel(BuildContext context) {
+    return JavascriptChannel(
+        name: 'Toaster',
+        onMessageReceived: (JavascriptMessage message) {
+          Scaffold.of(context).showSnackBar(
+            SnackBar(content: Text(message.message)),
+          );
+        });
+  }
+
+  Widget favoriteButton() {
+    return FutureBuilder<WebViewController>(
+        future: _controller.future,
+        builder: (BuildContext context,
+            AsyncSnapshot<WebViewController> controller) {
+          if (controller.hasData) {
+            return FloatingActionButton(
+              onPressed: () async {
+                final String url = await controller.data.currentUrl();
+                Scaffold.of(context).showSnackBar(
+                  SnackBar(content: Text('Favorited $url')),
+                );
+              },
+              child: const Icon(Icons.favorite),
+            );
+          }
+          return Container();
+        });
+  }
+}
+
+enum MenuOptions {
+  showUserAgent,
+  listCookies,
+  clearCookies,
+  addToCache,
+  listCache,
+  clearCache,
+  navigationDelegate,
+}
+
+class SampleMenu extends StatelessWidget {
+  SampleMenu(this.controller);
+
+  final Future<WebViewController> controller;
+  final CookieManager cookieManager = CookieManager();
+
+  @override
+  Widget build(BuildContext context) {
+    return FutureBuilder<WebViewController>(
+      future: controller,
+      builder:
+          (BuildContext context, AsyncSnapshot<WebViewController> controller) {
+        return PopupMenuButton<MenuOptions>(
+          onSelected: (MenuOptions value) {
+            switch (value) {
+              case MenuOptions.showUserAgent:
+                _onShowUserAgent(controller.data, context);
+                break;
+              case MenuOptions.listCookies:
+                _onListCookies(controller.data, context);
+                break;
+              case MenuOptions.clearCookies:
+                _onClearCookies(context);
+                break;
+              case MenuOptions.addToCache:
+                _onAddToCache(controller.data, context);
+                break;
+              case MenuOptions.listCache:
+                _onListCache(controller.data, context);
+                break;
+              case MenuOptions.clearCache:
+                _onClearCache(controller.data, context);
+                break;
+              case MenuOptions.navigationDelegate:
+                _onNavigationDelegateExample(controller.data, context);
+                break;
+            }
+          },
+          itemBuilder: (BuildContext context) => <PopupMenuItem<MenuOptions>>[
+            PopupMenuItem<MenuOptions>(
+              value: MenuOptions.showUserAgent,
+              child: const Text('Show user agent'),
+              enabled: controller.hasData,
+            ),
+            const PopupMenuItem<MenuOptions>(
+              value: MenuOptions.listCookies,
+              child: Text('List cookies'),
+            ),
+            const PopupMenuItem<MenuOptions>(
+              value: MenuOptions.clearCookies,
+              child: Text('Clear cookies'),
+            ),
+            const PopupMenuItem<MenuOptions>(
+              value: MenuOptions.addToCache,
+              child: Text('Add to cache'),
+            ),
+            const PopupMenuItem<MenuOptions>(
+              value: MenuOptions.listCache,
+              child: Text('List cache'),
+            ),
+            const PopupMenuItem<MenuOptions>(
+              value: MenuOptions.clearCache,
+              child: Text('Clear cache'),
+            ),
+            const PopupMenuItem<MenuOptions>(
+              value: MenuOptions.navigationDelegate,
+              child: Text('Navigation Delegate example'),
+            ),
+          ],
+        );
+      },
+    );
+  }
+
+  void _onShowUserAgent(
+      WebViewController controller, BuildContext context) async {
+    // Send a message with the user agent string to the Toaster JavaScript channel we registered
+    // with the WebView.
+    await controller.evaluateJavascript(
+        'Toaster.postMessage("User Agent: " + navigator.userAgent);');
+  }
+
+  void _onListCookies(
+      WebViewController controller, BuildContext context) async {
+    final String cookies =
+        await controller.evaluateJavascript('document.cookie');
+    Scaffold.of(context).showSnackBar(SnackBar(
+      content: Column(
+        mainAxisAlignment: MainAxisAlignment.end,
+        mainAxisSize: MainAxisSize.min,
+        children: <Widget>[
+          const Text('Cookies:'),
+          _getCookieList(cookies),
+        ],
+      ),
+    ));
+  }
+
+  void _onAddToCache(WebViewController controller, BuildContext context) async {
+    await controller.evaluateJavascript(
+        'caches.open("test_caches_entry"); localStorage["test_localStorage"] = "dummy_entry";');
+    Scaffold.of(context).showSnackBar(const SnackBar(
+      content: Text('Added a test entry to cache.'),
+    ));
+  }
+
+  void _onListCache(WebViewController controller, BuildContext context) async {
+    await controller.evaluateJavascript('caches.keys()'
+        '.then((cacheKeys) => JSON.stringify({"cacheKeys" : cacheKeys, "localStorage" : localStorage}))'
+        '.then((caches) => Toaster.postMessage(caches))');
+  }
+
+  void _onClearCache(WebViewController controller, BuildContext context) async {
+    await controller.clearCache();
+    Scaffold.of(context).showSnackBar(const SnackBar(
+      content: Text("Cache cleared."),
+    ));
+  }
+
+  void _onClearCookies(BuildContext context) async {
+    final bool hadCookies = await cookieManager.clearCookies();
+    String message = 'There were cookies. Now, they are gone!';
+    if (!hadCookies) {
+      message = 'There are no cookies.';
+    }
+    Scaffold.of(context).showSnackBar(SnackBar(
+      content: Text(message),
+    ));
+  }
+
+  void _onNavigationDelegateExample(
+      WebViewController controller, BuildContext context) async {
+    final String contentBase64 =
+        base64Encode(const Utf8Encoder().convert(kNavigationExamplePage));
+    await controller.loadUrl('data:text/html;base64,$contentBase64');
+  }
+
+  Widget _getCookieList(String cookies) {
+    if (cookies == null || cookies == '""') {
+      return Container();
+    }
+    final List<String> cookieList = cookies.split(';');
+    final Iterable<Text> cookieWidgets =
+        cookieList.map((String cookie) => Text(cookie));
+    return Column(
+      mainAxisAlignment: MainAxisAlignment.end,
+      mainAxisSize: MainAxisSize.min,
+      children: cookieWidgets.toList(),
+    );
+  }
+}
+
+class NavigationControls extends StatelessWidget {
+  const NavigationControls(this._webViewControllerFuture)
+      : assert(_webViewControllerFuture != null);
+
+  final Future<WebViewController> _webViewControllerFuture;
+
+  @override
+  Widget build(BuildContext context) {
+    return FutureBuilder<WebViewController>(
+      future: _webViewControllerFuture,
+      builder:
+          (BuildContext context, AsyncSnapshot<WebViewController> snapshot) {
+        final bool webViewReady =
+            snapshot.connectionState == ConnectionState.done;
+        final WebViewController controller = snapshot.data;
+        return Row(
+          children: <Widget>[
+            IconButton(
+              icon: const Icon(Icons.arrow_back_ios),
+              onPressed: !webViewReady
+                  ? null
+                  : () async {
+                      if (await controller.canGoBack()) {
+                        await controller.goBack();
+                      } else {
+                        Scaffold.of(context).showSnackBar(
+                          const SnackBar(content: Text("No back history item")),
+                        );
+                        return;
+                      }
+                    },
+            ),
+            IconButton(
+              icon: const Icon(Icons.arrow_forward_ios),
+              onPressed: !webViewReady
+                  ? null
+                  : () async {
+                      if (await controller.canGoForward()) {
+                        await controller.goForward();
+                      } else {
+                        Scaffold.of(context).showSnackBar(
+                          const SnackBar(
+                              content: Text("No forward history item")),
+                        );
+                        return;
+                      }
+                    },
+            ),
+            IconButton(
+              icon: const Icon(Icons.replay),
+              onPressed: !webViewReady
+                  ? null
+                  : () {
+                      controller.reload();
+                    },
+            ),
+          ],
+        );
+      },
+    );
+  }
+}

+ 24 - 0
example/pubspec.yaml

@@ -0,0 +1,24 @@
+name: webview_flutter_example
+description: Demonstrates how to use the webview_flutter plugin.
+
+environment:
+  sdk: ">=2.0.0-dev.68.0 <3.0.0"
+
+dependencies:
+  flutter:
+    sdk: flutter
+  webview_flutter:
+    path: ../
+
+dev_dependencies:
+  flutter_test:
+    sdk: flutter
+  flutter_driver:
+    sdk: flutter
+  e2e: "^0.2.0"
+  pedantic: ^1.8.0
+
+flutter:
+  uses-material-design: true
+  assets:
+    - assets/sample_audio.ogg

+ 726 - 0
example/test_driver/webview_flutter_e2e.dart

@@ -0,0 +1,726 @@
+// Copyright 2019, the Chromium project authors.  Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+import 'dart:async';
+import 'dart:convert';
+import 'dart:typed_data';
+
+import 'package:flutter/foundation.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter/widgets.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:webview_flutter/webview_flutter.dart';
+import 'package:e2e/e2e.dart';
+
+void main() {
+  E2EWidgetsFlutterBinding.ensureInitialized();
+
+  testWidgets('initalUrl', (WidgetTester tester) async {
+    final Completer<WebViewController> controllerCompleter =
+        Completer<WebViewController>();
+    await tester.pumpWidget(
+      Directionality(
+        textDirection: TextDirection.ltr,
+        child: WebView(
+          key: GlobalKey(),
+          initialUrl: 'https://flutter.dev/',
+          onWebViewCreated: (WebViewController controller) {
+            controllerCompleter.complete(controller);
+          },
+        ),
+      ),
+    );
+    final WebViewController controller = await controllerCompleter.future;
+    final String currentUrl = await controller.currentUrl();
+    expect(currentUrl, 'https://flutter.dev/');
+  });
+
+  testWidgets('loadUrl', (WidgetTester tester) async {
+    final Completer<WebViewController> controllerCompleter =
+        Completer<WebViewController>();
+    await tester.pumpWidget(
+      Directionality(
+        textDirection: TextDirection.ltr,
+        child: WebView(
+          key: GlobalKey(),
+          initialUrl: 'https://flutter.dev/',
+          onWebViewCreated: (WebViewController controller) {
+            controllerCompleter.complete(controller);
+          },
+        ),
+      ),
+    );
+    final WebViewController controller = await controllerCompleter.future;
+    await controller.loadUrl('https://www.google.com/');
+    final String currentUrl = await controller.currentUrl();
+    expect(currentUrl, 'https://www.google.com/');
+  });
+
+  // enable this once https://github.com/flutter/flutter/issues/31510
+  // is resolved.
+  testWidgets('loadUrl with headers', (WidgetTester tester) async {
+    final Completer<WebViewController> controllerCompleter =
+        Completer<WebViewController>();
+    final StreamController<String> pageStarts = StreamController<String>();
+    final StreamController<String> pageLoads = StreamController<String>();
+    await tester.pumpWidget(
+      Directionality(
+        textDirection: TextDirection.ltr,
+        child: WebView(
+          key: GlobalKey(),
+          initialUrl: 'https://flutter.dev/',
+          onWebViewCreated: (WebViewController controller) {
+            controllerCompleter.complete(controller);
+          },
+          javascriptMode: JavascriptMode.unrestricted,
+          onPageStarted: (String url) {
+            pageStarts.add(url);
+          },
+          onPageFinished: (String url) {
+            pageLoads.add(url);
+          },
+        ),
+      ),
+    );
+    final WebViewController controller = await controllerCompleter.future;
+    final Map<String, String> headers = <String, String>{
+      'test_header': 'flutter_test_header'
+    };
+    await controller.loadUrl('https://flutter-header-echo.herokuapp.com/',
+        headers: headers);
+    final String currentUrl = await controller.currentUrl();
+    expect(currentUrl, 'https://flutter-header-echo.herokuapp.com/');
+
+    await pageStarts.stream.firstWhere((String url) => url == currentUrl);
+    await pageLoads.stream.firstWhere((String url) => url == currentUrl);
+
+    final String content = await controller
+        .evaluateJavascript('document.documentElement.innerText');
+    expect(content.contains('flutter_test_header'), isTrue);
+  });
+
+  testWidgets('JavaScriptChannel', (WidgetTester tester) async {
+    final Completer<WebViewController> controllerCompleter =
+        Completer<WebViewController>();
+    final Completer<void> pageStarted = Completer<void>();
+    final Completer<void> pageLoaded = Completer<void>();
+    final List<String> messagesReceived = <String>[];
+    await tester.pumpWidget(
+      Directionality(
+        textDirection: TextDirection.ltr,
+        child: WebView(
+          key: GlobalKey(),
+          // This is the data URL for: '<!DOCTYPE html>'
+          initialUrl:
+              'data:text/html;charset=utf-8;base64,PCFET0NUWVBFIGh0bWw+',
+          onWebViewCreated: (WebViewController controller) {
+            controllerCompleter.complete(controller);
+          },
+          javascriptMode: JavascriptMode.unrestricted,
+          // TODO(iskakaushik): Remove this when collection literals makes it to stable.
+          // ignore: prefer_collection_literals
+          javascriptChannels: <JavascriptChannel>[
+            JavascriptChannel(
+              name: 'Echo',
+              onMessageReceived: (JavascriptMessage message) {
+                messagesReceived.add(message.message);
+              },
+            ),
+          ].toSet(),
+          onPageStarted: (String url) {
+            pageStarted.complete(null);
+          },
+          onPageFinished: (String url) {
+            pageLoaded.complete(null);
+          },
+        ),
+      ),
+    );
+    final WebViewController controller = await controllerCompleter.future;
+    await pageStarted.future;
+    await pageLoaded.future;
+
+    expect(messagesReceived, isEmpty);
+    await controller.evaluateJavascript('Echo.postMessage("hello");');
+    expect(messagesReceived, equals(<String>['hello']));
+  });
+
+  testWidgets('resize webview', (WidgetTester tester) async {
+    final String resizeTest = '''
+        <!DOCTYPE html><html>
+        <head><title>Resize test</title>
+          <script type="text/javascript">
+            function onResize() {
+              Resize.postMessage("resize");
+            }
+            function onLoad() {
+              window.onresize = onResize;
+            }
+          </script>
+        </head>
+        <body onload="onLoad();" bgColor="blue">
+        </body>
+        </html>
+      ''';
+    final String resizeTestBase64 =
+        base64Encode(const Utf8Encoder().convert(resizeTest));
+    final Completer<void> resizeCompleter = Completer<void>();
+    final Completer<void> pageStarted = Completer<void>();
+    final Completer<void> pageLoaded = Completer<void>();
+    final Completer<WebViewController> controllerCompleter =
+        Completer<WebViewController>();
+    final GlobalKey key = GlobalKey();
+
+    final WebView webView = WebView(
+      key: key,
+      initialUrl: 'data:text/html;charset=utf-8;base64,$resizeTestBase64',
+      onWebViewCreated: (WebViewController controller) {
+        controllerCompleter.complete(controller);
+      },
+      // TODO(iskakaushik): Remove this when collection literals makes it to stable.
+      // ignore: prefer_collection_literals
+      javascriptChannels: <JavascriptChannel>[
+        JavascriptChannel(
+          name: 'Resize',
+          onMessageReceived: (JavascriptMessage message) {
+            resizeCompleter.complete(true);
+          },
+        ),
+      ].toSet(),
+      onPageStarted: (String url) {
+        pageStarted.complete(null);
+      },
+      onPageFinished: (String url) {
+        pageLoaded.complete(null);
+      },
+      javascriptMode: JavascriptMode.unrestricted,
+    );
+
+    await tester.pumpWidget(
+      Directionality(
+        textDirection: TextDirection.ltr,
+        child: Column(
+          children: <Widget>[
+            SizedBox(
+              width: 200,
+              height: 200,
+              child: webView,
+            ),
+          ],
+        ),
+      ),
+    );
+
+    await controllerCompleter.future;
+    await pageStarted.future;
+    await pageLoaded.future;
+
+    expect(resizeCompleter.isCompleted, false);
+
+    await tester.pumpWidget(
+      Directionality(
+        textDirection: TextDirection.ltr,
+        child: Column(
+          children: <Widget>[
+            SizedBox(
+              width: 400,
+              height: 400,
+              child: webView,
+            ),
+          ],
+        ),
+      ),
+    );
+
+    await resizeCompleter.future;
+  });
+
+  testWidgets('set custom userAgent', (WidgetTester tester) async {
+    final Completer<WebViewController> controllerCompleter1 =
+        Completer<WebViewController>();
+    final GlobalKey _globalKey = GlobalKey();
+    await tester.pumpWidget(
+      Directionality(
+        textDirection: TextDirection.ltr,
+        child: WebView(
+          key: _globalKey,
+          initialUrl: 'about:blank',
+          javascriptMode: JavascriptMode.unrestricted,
+          userAgent: 'Custom_User_Agent1',
+          onWebViewCreated: (WebViewController controller) {
+            controllerCompleter1.complete(controller);
+          },
+        ),
+      ),
+    );
+    final WebViewController controller1 = await controllerCompleter1.future;
+    final String customUserAgent1 = await _getUserAgent(controller1);
+    expect(customUserAgent1, 'Custom_User_Agent1');
+    // rebuild the WebView with a different user agent.
+    await tester.pumpWidget(
+      Directionality(
+        textDirection: TextDirection.ltr,
+        child: WebView(
+          key: _globalKey,
+          initialUrl: 'about:blank',
+          javascriptMode: JavascriptMode.unrestricted,
+          userAgent: 'Custom_User_Agent2',
+        ),
+      ),
+    );
+
+    final String customUserAgent2 = await _getUserAgent(controller1);
+    expect(customUserAgent2, 'Custom_User_Agent2');
+  });
+
+  testWidgets('use default platform userAgent after webView is rebuilt',
+      (WidgetTester tester) async {
+    final Completer<WebViewController> controllerCompleter =
+        Completer<WebViewController>();
+    final GlobalKey _globalKey = GlobalKey();
+    // Build the webView with no user agent to get the default platform user agent.
+    await tester.pumpWidget(
+      Directionality(
+        textDirection: TextDirection.ltr,
+        child: WebView(
+          key: _globalKey,
+          initialUrl: 'https://flutter.dev/',
+          javascriptMode: JavascriptMode.unrestricted,
+          onWebViewCreated: (WebViewController controller) {
+            controllerCompleter.complete(controller);
+          },
+        ),
+      ),
+    );
+    final WebViewController controller = await controllerCompleter.future;
+    final String defaultPlatformUserAgent = await _getUserAgent(controller);
+    // rebuild the WebView with a custom user agent.
+    await tester.pumpWidget(
+      Directionality(
+        textDirection: TextDirection.ltr,
+        child: WebView(
+          key: _globalKey,
+          initialUrl: 'about:blank',
+          javascriptMode: JavascriptMode.unrestricted,
+          userAgent: 'Custom_User_Agent',
+        ),
+      ),
+    );
+    final String customUserAgent = await _getUserAgent(controller);
+    expect(customUserAgent, 'Custom_User_Agent');
+    // rebuilds the WebView with no user agent.
+    await tester.pumpWidget(
+      Directionality(
+        textDirection: TextDirection.ltr,
+        child: WebView(
+          key: _globalKey,
+          initialUrl: 'about:blank',
+          javascriptMode: JavascriptMode.unrestricted,
+        ),
+      ),
+    );
+
+    final String customUserAgent2 = await _getUserAgent(controller);
+    expect(customUserAgent2, defaultPlatformUserAgent);
+  });
+
+  group('Media playback policy', () {
+    String audioTestBase64;
+    setUpAll(() async {
+      final ByteData audioData =
+          await rootBundle.load('assets/sample_audio.ogg');
+      final String base64AudioData =
+          base64Encode(Uint8List.view(audioData.buffer));
+      final String audioTest = '''
+        <!DOCTYPE html><html>
+        <head><title>Audio auto play</title>
+          <script type="text/javascript">
+            function play() {
+              var audio = document.getElementById("audio");
+              audio.play();
+            }
+            function isPaused() {
+              var audio = document.getElementById("audio");
+              return audio.paused;
+            }
+          </script>
+        </head>
+        <body onload="play();">
+        <audio controls id="audio">
+          <source src="data:audio/ogg;charset=utf-8;base64,$base64AudioData">
+        </audio>
+        </body>
+        </html>
+      ''';
+      audioTestBase64 = base64Encode(const Utf8Encoder().convert(audioTest));
+    });
+
+    testWidgets('Auto media playback', (WidgetTester tester) async {
+      Completer<WebViewController> controllerCompleter =
+          Completer<WebViewController>();
+      Completer<void> pageStarted = Completer<void>();
+      Completer<void> pageLoaded = Completer<void>();
+
+      await tester.pumpWidget(
+        Directionality(
+          textDirection: TextDirection.ltr,
+          child: WebView(
+            key: GlobalKey(),
+            initialUrl: 'data:text/html;charset=utf-8;base64,$audioTestBase64',
+            onWebViewCreated: (WebViewController controller) {
+              controllerCompleter.complete(controller);
+            },
+            javascriptMode: JavascriptMode.unrestricted,
+            onPageStarted: (String url) {
+              pageStarted.complete(null);
+            },
+            onPageFinished: (String url) {
+              pageLoaded.complete(null);
+            },
+            initialMediaPlaybackPolicy: AutoMediaPlaybackPolicy.always_allow,
+          ),
+        ),
+      );
+      WebViewController controller = await controllerCompleter.future;
+      await pageStarted.future;
+      await pageLoaded.future;
+
+      String isPaused = await controller.evaluateJavascript('isPaused();');
+      expect(isPaused, _webviewBool(false));
+
+      controllerCompleter = Completer<WebViewController>();
+      pageStarted = Completer<void>();
+      pageLoaded = Completer<void>();
+
+      // We change the key to re-create a new webview as we change the initialMediaPlaybackPolicy
+      await tester.pumpWidget(
+        Directionality(
+          textDirection: TextDirection.ltr,
+          child: WebView(
+            key: GlobalKey(),
+            initialUrl: 'data:text/html;charset=utf-8;base64,$audioTestBase64',
+            onWebViewCreated: (WebViewController controller) {
+              controllerCompleter.complete(controller);
+            },
+            javascriptMode: JavascriptMode.unrestricted,
+            onPageStarted: (String url) {
+              pageStarted.complete(null);
+            },
+            onPageFinished: (String url) {
+              pageLoaded.complete(null);
+            },
+            initialMediaPlaybackPolicy:
+                AutoMediaPlaybackPolicy.require_user_action_for_all_media_types,
+          ),
+        ),
+      );
+
+      controller = await controllerCompleter.future;
+      await pageStarted.future;
+      await pageLoaded.future;
+
+      isPaused = await controller.evaluateJavascript('isPaused();');
+      expect(isPaused, _webviewBool(true));
+    });
+
+    testWidgets('Changes to initialMediaPlaybackPolocy are ignored',
+        (WidgetTester tester) async {
+      final Completer<WebViewController> controllerCompleter =
+          Completer<WebViewController>();
+      Completer<void> pageStarted = Completer<void>();
+      Completer<void> pageLoaded = Completer<void>();
+
+      final GlobalKey key = GlobalKey();
+      await tester.pumpWidget(
+        Directionality(
+          textDirection: TextDirection.ltr,
+          child: WebView(
+            key: key,
+            initialUrl: 'data:text/html;charset=utf-8;base64,$audioTestBase64',
+            onWebViewCreated: (WebViewController controller) {
+              controllerCompleter.complete(controller);
+            },
+            javascriptMode: JavascriptMode.unrestricted,
+            onPageStarted: (String url) {
+              pageStarted.complete(null);
+            },
+            onPageFinished: (String url) {
+              pageLoaded.complete(null);
+            },
+            initialMediaPlaybackPolicy: AutoMediaPlaybackPolicy.always_allow,
+          ),
+        ),
+      );
+      final WebViewController controller = await controllerCompleter.future;
+      await pageStarted.future;
+      await pageLoaded.future;
+
+      String isPaused = await controller.evaluateJavascript('isPaused();');
+      expect(isPaused, _webviewBool(false));
+
+      pageStarted = Completer<void>();
+      pageLoaded = Completer<void>();
+
+      await tester.pumpWidget(
+        Directionality(
+          textDirection: TextDirection.ltr,
+          child: WebView(
+            key: key,
+            initialUrl: 'data:text/html;charset=utf-8;base64,$audioTestBase64',
+            onWebViewCreated: (WebViewController controller) {
+              controllerCompleter.complete(controller);
+            },
+            javascriptMode: JavascriptMode.unrestricted,
+            onPageStarted: (String url) {
+              pageStarted.complete(null);
+            },
+            onPageFinished: (String url) {
+              pageLoaded.complete(null);
+            },
+            initialMediaPlaybackPolicy:
+                AutoMediaPlaybackPolicy.require_user_action_for_all_media_types,
+          ),
+        ),
+      );
+
+      await controller.reload();
+
+      await pageStarted.future;
+      await pageLoaded.future;
+
+      isPaused = await controller.evaluateJavascript('isPaused();');
+      expect(isPaused, _webviewBool(false));
+    });
+  });
+
+  testWidgets('getTitle', (WidgetTester tester) async {
+    final String getTitleTest = '''
+        <!DOCTYPE html><html>
+        <head><title>Some title</title>
+        </head>
+        <body>
+        </body>
+        </html>
+      ''';
+    final String getTitleTestBase64 =
+        base64Encode(const Utf8Encoder().convert(getTitleTest));
+    final Completer<void> pageStarted = Completer<void>();
+    final Completer<void> pageLoaded = Completer<void>();
+    final Completer<WebViewController> controllerCompleter =
+        Completer<WebViewController>();
+
+    await tester.pumpWidget(
+      Directionality(
+        textDirection: TextDirection.ltr,
+        child: WebView(
+          initialUrl: 'data:text/html;charset=utf-8;base64,$getTitleTestBase64',
+          onWebViewCreated: (WebViewController controller) {
+            controllerCompleter.complete(controller);
+          },
+          onPageStarted: (String url) {
+            pageStarted.complete(null);
+          },
+          onPageFinished: (String url) {
+            pageLoaded.complete(null);
+          },
+        ),
+      ),
+    );
+
+    final WebViewController controller = await controllerCompleter.future;
+    await pageStarted.future;
+    await pageLoaded.future;
+
+    final String title = await controller.getTitle();
+    expect(title, 'Some title');
+  });
+
+  group('NavigationDelegate', () {
+    final String blankPage = "<!DOCTYPE html><head></head><body></body></html>";
+    final String blankPageEncoded = 'data:text/html;charset=utf-8;base64,' +
+        base64Encode(const Utf8Encoder().convert(blankPage));
+
+    testWidgets('can allow requests', (WidgetTester tester) async {
+      final Completer<WebViewController> controllerCompleter =
+          Completer<WebViewController>();
+      final StreamController<String> pageLoads =
+          StreamController<String>.broadcast();
+      await tester.pumpWidget(
+        Directionality(
+          textDirection: TextDirection.ltr,
+          child: WebView(
+            key: GlobalKey(),
+            initialUrl: blankPageEncoded,
+            onWebViewCreated: (WebViewController controller) {
+              controllerCompleter.complete(controller);
+            },
+            javascriptMode: JavascriptMode.unrestricted,
+            navigationDelegate: (NavigationRequest request) {
+              return (request.url.contains('youtube.com'))
+                  ? NavigationDecision.prevent
+                  : NavigationDecision.navigate;
+            },
+            onPageFinished: (String url) => pageLoads.add(url),
+          ),
+        ),
+      );
+
+      await pageLoads.stream.first; // Wait for initial page load.
+      final WebViewController controller = await controllerCompleter.future;
+      await controller
+          .evaluateJavascript('location.href = "https://www.google.com/"');
+
+      await pageLoads.stream.first; // Wait for the next page load.
+      final String currentUrl = await controller.currentUrl();
+      expect(currentUrl, 'https://www.google.com/');
+    });
+
+    testWidgets('can block requests', (WidgetTester tester) async {
+      final Completer<WebViewController> controllerCompleter =
+          Completer<WebViewController>();
+      final StreamController<String> pageLoads =
+          StreamController<String>.broadcast();
+      await tester.pumpWidget(
+        Directionality(
+          textDirection: TextDirection.ltr,
+          child: WebView(
+            key: GlobalKey(),
+            initialUrl: blankPageEncoded,
+            onWebViewCreated: (WebViewController controller) {
+              controllerCompleter.complete(controller);
+            },
+            javascriptMode: JavascriptMode.unrestricted,
+            navigationDelegate: (NavigationRequest request) {
+              return (request.url.contains('youtube.com'))
+                  ? NavigationDecision.prevent
+                  : NavigationDecision.navigate;
+            },
+            onPageFinished: (String url) => pageLoads.add(url),
+          ),
+        ),
+      );
+
+      await pageLoads.stream.first; // Wait for initial page load.
+      final WebViewController controller = await controllerCompleter.future;
+      await controller
+          .evaluateJavascript('location.href = "https://www.youtube.com/"');
+
+      // There should never be any second page load, since our new URL is
+      // blocked. Still wait for a potential page change for some time in order
+      // to give the test a chance to fail.
+      await pageLoads.stream.first
+          .timeout(const Duration(milliseconds: 500), onTimeout: () => null);
+      final String currentUrl = await controller.currentUrl();
+      expect(currentUrl, isNot(contains('youtube.com')));
+    });
+
+    testWidgets('supports asynchronous decisions', (WidgetTester tester) async {
+      final Completer<WebViewController> controllerCompleter =
+          Completer<WebViewController>();
+      final StreamController<String> pageLoads =
+          StreamController<String>.broadcast();
+      await tester.pumpWidget(
+        Directionality(
+          textDirection: TextDirection.ltr,
+          child: WebView(
+            key: GlobalKey(),
+            initialUrl: blankPageEncoded,
+            onWebViewCreated: (WebViewController controller) {
+              controllerCompleter.complete(controller);
+            },
+            javascriptMode: JavascriptMode.unrestricted,
+            navigationDelegate: (NavigationRequest request) async {
+              NavigationDecision decision = NavigationDecision.prevent;
+              decision = await Future<NavigationDecision>.delayed(
+                  const Duration(milliseconds: 10),
+                  () => NavigationDecision.navigate);
+              return decision;
+            },
+            onPageFinished: (String url) => pageLoads.add(url),
+          ),
+        ),
+      );
+
+      await pageLoads.stream.first; // Wait for initial page load.
+      final WebViewController controller = await controllerCompleter.future;
+      await controller
+          .evaluateJavascript('location.href = "https://www.google.com"');
+
+      await pageLoads.stream.first; // Wait for second page to load.
+      final String currentUrl = await controller.currentUrl();
+      expect(currentUrl, 'https://www.google.com/');
+    });
+  });
+
+  testWidgets('launches with gestureNavigationEnabled on iOS',
+      (WidgetTester tester) async {
+    final Completer<WebViewController> controllerCompleter =
+        Completer<WebViewController>();
+    await tester.pumpWidget(
+      Directionality(
+        textDirection: TextDirection.ltr,
+        child: SizedBox(
+          width: 400,
+          height: 300,
+          child: WebView(
+            key: GlobalKey(),
+            initialUrl: 'https://flutter.dev/',
+            gestureNavigationEnabled: true,
+            onWebViewCreated: (WebViewController controller) {
+              controllerCompleter.complete(controller);
+            },
+          ),
+        ),
+      ),
+    );
+    final WebViewController controller = await controllerCompleter.future;
+    final String currentUrl = await controller.currentUrl();
+    expect(currentUrl, 'https://flutter.dev/');
+  });
+
+  testWidgets('target _blank opens in same window',
+      (WidgetTester tester) async {
+    final Completer<WebViewController> controllerCompleter =
+        Completer<WebViewController>();
+    final Completer<void> pageLoaded = Completer<void>();
+    await tester.pumpWidget(
+      Directionality(
+        textDirection: TextDirection.ltr,
+        child: WebView(
+          key: GlobalKey(),
+          onWebViewCreated: (WebViewController controller) {
+            controllerCompleter.complete(controller);
+          },
+          javascriptMode: JavascriptMode.unrestricted,
+          onPageFinished: (String url) {
+            pageLoaded.complete(null);
+          },
+        ),
+      ),
+    );
+    final WebViewController controller = await controllerCompleter.future;
+    await controller.evaluateJavascript('window.open("about:blank", "_blank")');
+    await pageLoaded.future;
+    final String currentUrl = await controller.currentUrl();
+    expect(currentUrl, 'about:blank');
+  });
+}
+
+// JavaScript booleans evaluate to different string values on Android and iOS.
+// This utility method returns the string boolean value of the current platform.
+String _webviewBool(bool value) {
+  if (defaultTargetPlatform == TargetPlatform.iOS) {
+    return value ? '1' : '0';
+  }
+  return value ? 'true' : 'false';
+}
+
+/// Returns the value used for the HTTP User-Agent: request header in subsequent HTTP requests.
+Future<String> _getUserAgent(WebViewController controller) async {
+  if (defaultTargetPlatform == TargetPlatform.iOS) {
+    return await controller.evaluateJavascript('navigator.userAgent;');
+  }
+  return jsonDecode(
+      await controller.evaluateJavascript('navigator.userAgent;'));
+}

+ 16 - 0
example/test_driver/webview_flutter_e2e_test.dart

@@ -0,0 +1,16 @@
+// Copyright 2019, the Chromium project authors.  Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+import 'dart:async';
+import 'dart:io';
+
+import 'package:flutter_driver/flutter_driver.dart';
+
+Future<void> main() async {
+  final FlutterDriver driver = await FlutterDriver.connect();
+  final String result =
+      await driver.requestData(null, timeout: const Duration(minutes: 1));
+  await driver.close();
+  exit(result == 'pass' ? 0 : 1);
+}

+ 0 - 0
ios/Assets/.gitkeep


+ 14 - 0
ios/Classes/FLTCookieManager.h

@@ -0,0 +1,14 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#import <Flutter/Flutter.h>
+#import <WebKit/WebKit.h>
+
+NS_ASSUME_NONNULL_BEGIN
+
+@interface FLTCookieManager : NSObject <FlutterPlugin>
+
+@end
+
+NS_ASSUME_NONNULL_END

+ 49 - 0
ios/Classes/FLTCookieManager.m

@@ -0,0 +1,49 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#import "FLTCookieManager.h"
+
+@implementation FLTCookieManager {
+}
+
++ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar> *)registrar {
+  FLTCookieManager *instance = [[FLTCookieManager alloc] init];
+
+  FlutterMethodChannel *channel =
+      [FlutterMethodChannel methodChannelWithName:@"plugins.flutter.io/cookie_manager"
+                                  binaryMessenger:[registrar messenger]];
+  [registrar addMethodCallDelegate:instance channel:channel];
+}
+
+- (void)handleMethodCall:(FlutterMethodCall *)call result:(FlutterResult)result {
+  if ([[call method] isEqualToString:@"clearCookies"]) {
+    [self clearCookies:result];
+  } else {
+    result(FlutterMethodNotImplemented);
+  }
+}
+
+- (void)clearCookies:(FlutterResult)result {
+  if (@available(iOS 9.0, *)) {
+    NSSet<NSString *> *websiteDataTypes = [NSSet setWithObject:WKWebsiteDataTypeCookies];
+    WKWebsiteDataStore *dataStore = [WKWebsiteDataStore defaultDataStore];
+
+    void (^deleteAndNotify)(NSArray<WKWebsiteDataRecord *> *) =
+        ^(NSArray<WKWebsiteDataRecord *> *cookies) {
+          BOOL hasCookies = cookies.count > 0;
+          [dataStore removeDataOfTypes:websiteDataTypes
+                        forDataRecords:cookies
+                     completionHandler:^{
+                       result(@(hasCookies));
+                     }];
+        };
+
+    [dataStore fetchDataRecordsOfTypes:websiteDataTypes completionHandler:deleteAndNotify];
+  } else {
+    // support for iOS8 tracked in https://github.com/flutter/flutter/issues/27624.
+    NSLog(@"Clearing cookies is not supported for Flutter WebViews prior to iOS 9.");
+  }
+}
+
+@end

+ 21 - 0
ios/Classes/FLTWKNavigationDelegate.h

@@ -0,0 +1,21 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#import <Flutter/Flutter.h>
+#import <WebKit/WebKit.h>
+
+NS_ASSUME_NONNULL_BEGIN
+
+@interface FLTWKNavigationDelegate : NSObject <WKNavigationDelegate>
+
+- (instancetype)initWithChannel:(FlutterMethodChannel*)channel;
+
+/**
+ * Whether to delegate navigation decisions over the method channel.
+ */
+@property(nonatomic, assign) BOOL hasDartNavigationDelegate;
+
+@end
+
+NS_ASSUME_NONNULL_END

+ 68 - 0
ios/Classes/FLTWKNavigationDelegate.m

@@ -0,0 +1,68 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#import "FLTWKNavigationDelegate.h"
+
+@implementation FLTWKNavigationDelegate {
+  FlutterMethodChannel* _methodChannel;
+}
+
+- (instancetype)initWithChannel:(FlutterMethodChannel*)channel {
+  self = [super init];
+  if (self) {
+    _methodChannel = channel;
+  }
+  return self;
+}
+
+#pragma mark - WKNavigationDelegate conformance
+
+- (void)webView:(WKWebView*)webView didStartProvisionalNavigation:(WKNavigation*)navigation {
+  [_methodChannel invokeMethod:@"onPageStarted" arguments:@{@"url" : webView.URL.absoluteString}];
+}
+
+- (void)webView:(WKWebView*)webView
+    decidePolicyForNavigationAction:(WKNavigationAction*)navigationAction
+                    decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
+  if (!self.hasDartNavigationDelegate) {
+    decisionHandler(WKNavigationActionPolicyAllow);
+    return;
+  }
+  NSDictionary* arguments = @{
+    @"url" : navigationAction.request.URL.absoluteString,
+    @"isForMainFrame" : @(navigationAction.targetFrame.isMainFrame)
+  };
+  [_methodChannel invokeMethod:@"navigationRequest"
+                     arguments:arguments
+                        result:^(id _Nullable result) {
+                          if ([result isKindOfClass:[FlutterError class]]) {
+                            NSLog(@"navigationRequest has unexpectedly completed with an error, "
+                                  @"allowing navigation.");
+                            decisionHandler(WKNavigationActionPolicyAllow);
+                            return;
+                          }
+                          if (result == FlutterMethodNotImplemented) {
+                            NSLog(@"navigationRequest was unexepectedly not implemented: %@, "
+                                  @"allowing navigation.",
+                                  result);
+                            decisionHandler(WKNavigationActionPolicyAllow);
+                            return;
+                          }
+                          if (![result isKindOfClass:[NSNumber class]]) {
+                            NSLog(@"navigationRequest unexpectedly returned a non boolean value: "
+                                  @"%@, allowing navigation.",
+                                  result);
+                            decisionHandler(WKNavigationActionPolicyAllow);
+                            return;
+                          }
+                          NSNumber* typedResult = result;
+                          decisionHandler([typedResult boolValue] ? WKNavigationActionPolicyAllow
+                                                                  : WKNavigationActionPolicyCancel);
+                        }];
+}
+
+- (void)webView:(WKWebView*)webView didFinishNavigation:(WKNavigation*)navigation {
+  [_methodChannel invokeMethod:@"onPageFinished" arguments:@{@"url" : webView.URL.absoluteString}];
+}
+@end

+ 8 - 0
ios/Classes/FLTWebViewFlutterPlugin.h

@@ -0,0 +1,8 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#import <Flutter/Flutter.h>
+
+@interface FLTWebViewFlutterPlugin : NSObject <FlutterPlugin>
+@end

+ 18 - 0
ios/Classes/FLTWebViewFlutterPlugin.m

@@ -0,0 +1,18 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#import "FLTWebViewFlutterPlugin.h"
+#import "FLTCookieManager.h"
+#import "FlutterWebView.h"
+
+@implementation FLTWebViewFlutterPlugin
+
++ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
+  FLTWebViewFactory* webviewFactory =
+      [[FLTWebViewFactory alloc] initWithMessenger:registrar.messenger];
+  [registrar registerViewFactory:webviewFactory withId:@"plugins.flutter.io/webview"];
+  [FLTCookieManager registerWithRegistrar:registrar];
+}
+
+@end

+ 32 - 0
ios/Classes/FlutterWebView.h

@@ -0,0 +1,32 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#import <Flutter/Flutter.h>
+#import <WebKit/WebKit.h>
+
+NS_ASSUME_NONNULL_BEGIN
+
+@interface FLTWebViewController : NSObject <FlutterPlatformView, WKUIDelegate>
+
+- (instancetype)initWithFrame:(CGRect)frame
+               viewIdentifier:(int64_t)viewId
+                    arguments:(id _Nullable)args
+              binaryMessenger:(NSObject<FlutterBinaryMessenger>*)messenger;
+
+- (UIView*)view;
+@end
+
+@interface FLTWebViewFactory : NSObject <FlutterPlatformViewFactory>
+- (instancetype)initWithMessenger:(NSObject<FlutterBinaryMessenger>*)messenger;
+@end
+
+/**
+ * The WkWebView used for the plugin.
+ *
+ * This class overrides some methods in `WKWebView` to serve the needs for the plugin.
+ */
+@interface FLTWKWebView : WKWebView
+@end
+
+NS_ASSUME_NONNULL_END

+ 415 - 0
ios/Classes/FlutterWebView.m

@@ -0,0 +1,415 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#import "FlutterWebView.h"
+#import "FLTWKNavigationDelegate.h"
+#import "JavaScriptChannelHandler.h"
+
+@implementation FLTWebViewFactory {
+  NSObject<FlutterBinaryMessenger>* _messenger;
+}
+
+- (instancetype)initWithMessenger:(NSObject<FlutterBinaryMessenger>*)messenger {
+  self = [super init];
+  if (self) {
+    _messenger = messenger;
+  }
+  return self;
+}
+
+- (NSObject<FlutterMessageCodec>*)createArgsCodec {
+  return [FlutterStandardMessageCodec sharedInstance];
+}
+
+- (NSObject<FlutterPlatformView>*)createWithFrame:(CGRect)frame
+                                   viewIdentifier:(int64_t)viewId
+                                        arguments:(id _Nullable)args {
+  FLTWebViewController* webviewController = [[FLTWebViewController alloc] initWithFrame:frame
+                                                                         viewIdentifier:viewId
+                                                                              arguments:args
+                                                                        binaryMessenger:_messenger];
+  return webviewController;
+}
+
+@end
+
+@implementation FLTWKWebView
+
+- (void)setFrame:(CGRect)frame {
+  [super setFrame:frame];
+  self.scrollView.contentInset = UIEdgeInsetsZero;
+  // We don't want the contentInsets to be adjusted by iOS, flutter should always take control of
+  // webview's contentInsets.
+  // self.scrollView.contentInset = UIEdgeInsetsZero;
+  if (@available(iOS 11, *)) {
+    // Above iOS 11, adjust contentInset to compensate the adjustedContentInset so the sum will
+    // always be 0.
+    if (UIEdgeInsetsEqualToEdgeInsets(self.scrollView.adjustedContentInset, UIEdgeInsetsZero)) {
+      return;
+    }
+    UIEdgeInsets insetToAdjust = self.scrollView.adjustedContentInset;
+    self.scrollView.contentInset = UIEdgeInsetsMake(-insetToAdjust.top, -insetToAdjust.left,
+                                                    -insetToAdjust.bottom, -insetToAdjust.right);
+  }
+}
+
+@end
+
+@implementation FLTWebViewController {
+  FLTWKWebView* _webView;
+  int64_t _viewId;
+  FlutterMethodChannel* _channel;
+  NSString* _currentUrl;
+  // The set of registered JavaScript channel names.
+  NSMutableSet* _javaScriptChannelNames;
+  FLTWKNavigationDelegate* _navigationDelegate;
+}
+
+- (instancetype)initWithFrame:(CGRect)frame
+               viewIdentifier:(int64_t)viewId
+                    arguments:(id _Nullable)args
+              binaryMessenger:(NSObject<FlutterBinaryMessenger>*)messenger {
+  if (self = [super init]) {
+    _viewId = viewId;
+
+    NSString* channelName = [NSString stringWithFormat:@"plugins.flutter.io/webview_%lld", viewId];
+    _channel = [FlutterMethodChannel methodChannelWithName:channelName binaryMessenger:messenger];
+    _javaScriptChannelNames = [[NSMutableSet alloc] init];
+
+    WKUserContentController* userContentController = [[WKUserContentController alloc] init];
+    if ([args[@"javascriptChannelNames"] isKindOfClass:[NSArray class]]) {
+      NSArray* javaScriptChannelNames = args[@"javascriptChannelNames"];
+      [_javaScriptChannelNames addObjectsFromArray:javaScriptChannelNames];
+      [self registerJavaScriptChannels:_javaScriptChannelNames controller:userContentController];
+    }
+
+    NSDictionary<NSString*, id>* settings = args[@"settings"];
+
+    WKWebViewConfiguration* configuration = [[WKWebViewConfiguration alloc] init];
+    configuration.userContentController = userContentController;
+    [self updateAutoMediaPlaybackPolicy:args[@"autoMediaPlaybackPolicy"]
+                        inConfiguration:configuration];
+
+    _webView = [[FLTWKWebView alloc] initWithFrame:frame configuration:configuration];
+    _navigationDelegate = [[FLTWKNavigationDelegate alloc] initWithChannel:_channel];
+    _webView.UIDelegate = self;
+    _webView.navigationDelegate = _navigationDelegate;
+    __weak __typeof__(self) weakSelf = self;
+    [_channel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {
+      [weakSelf onMethodCall:call result:result];
+    }];
+
+    if (@available(iOS 11.0, *)) {
+      _webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
+      if (@available(iOS 13.0, *)) {
+        _webView.scrollView.automaticallyAdjustsScrollIndicatorInsets = NO;
+      }
+    }
+
+    [self applySettings:settings];
+    // TODO(amirh): return an error if apply settings failed once it's possible to do so.
+    // https://github.com/flutter/flutter/issues/36228
+
+    NSString* initialUrl = args[@"initialUrl"];
+    if ([initialUrl isKindOfClass:[NSString class]]) {
+      [self loadUrl:initialUrl];
+    }
+  }
+  return self;
+}
+
+- (UIView*)view {
+  return _webView;
+}
+
+- (void)onMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result {
+  if ([[call method] isEqualToString:@"updateSettings"]) {
+    [self onUpdateSettings:call result:result];
+  } else if ([[call method] isEqualToString:@"loadUrl"]) {
+    [self onLoadUrl:call result:result];
+  } else if ([[call method] isEqualToString:@"canGoBack"]) {
+    [self onCanGoBack:call result:result];
+  } else if ([[call method] isEqualToString:@"canGoForward"]) {
+    [self onCanGoForward:call result:result];
+  } else if ([[call method] isEqualToString:@"goBack"]) {
+    [self onGoBack:call result:result];
+  } else if ([[call method] isEqualToString:@"goForward"]) {
+    [self onGoForward:call result:result];
+  } else if ([[call method] isEqualToString:@"reload"]) {
+    [self onReload:call result:result];
+  } else if ([[call method] isEqualToString:@"currentUrl"]) {
+    [self onCurrentUrl:call result:result];
+  } else if ([[call method] isEqualToString:@"evaluateJavascript"]) {
+    [self onEvaluateJavaScript:call result:result];
+  } else if ([[call method] isEqualToString:@"addJavascriptChannels"]) {
+    [self onAddJavaScriptChannels:call result:result];
+  } else if ([[call method] isEqualToString:@"removeJavascriptChannels"]) {
+    [self onRemoveJavaScriptChannels:call result:result];
+  } else if ([[call method] isEqualToString:@"clearCache"]) {
+    [self clearCache:result];
+  } else if ([[call method] isEqualToString:@"getTitle"]) {
+    [self onGetTitle:result];
+  } else {
+    result(FlutterMethodNotImplemented);
+  }
+}
+
+- (void)onUpdateSettings:(FlutterMethodCall*)call result:(FlutterResult)result {
+  NSString* error = [self applySettings:[call arguments]];
+  if (error == nil) {
+    result(nil);
+    return;
+  }
+  result([FlutterError errorWithCode:@"updateSettings_failed" message:error details:nil]);
+}
+
+- (void)onLoadUrl:(FlutterMethodCall*)call result:(FlutterResult)result {
+  if (![self loadRequest:[call arguments]]) {
+    result([FlutterError
+        errorWithCode:@"loadUrl_failed"
+              message:@"Failed parsing the URL"
+              details:[NSString stringWithFormat:@"Request was: '%@'", [call arguments]]]);
+  } else {
+    result(nil);
+  }
+}
+
+- (void)onCanGoBack:(FlutterMethodCall*)call result:(FlutterResult)result {
+  BOOL canGoBack = [_webView canGoBack];
+  result([NSNumber numberWithBool:canGoBack]);
+}
+
+- (void)onCanGoForward:(FlutterMethodCall*)call result:(FlutterResult)result {
+  BOOL canGoForward = [_webView canGoForward];
+  result([NSNumber numberWithBool:canGoForward]);
+}
+
+- (void)onGoBack:(FlutterMethodCall*)call result:(FlutterResult)result {
+  [_webView goBack];
+  result(nil);
+}
+
+- (void)onGoForward:(FlutterMethodCall*)call result:(FlutterResult)result {
+  [_webView goForward];
+  result(nil);
+}
+
+- (void)onReload:(FlutterMethodCall*)call result:(FlutterResult)result {
+  [_webView reload];
+  result(nil);
+}
+
+- (void)onCurrentUrl:(FlutterMethodCall*)call result:(FlutterResult)result {
+  _currentUrl = [[_webView URL] absoluteString];
+  result(_currentUrl);
+}
+
+- (void)onEvaluateJavaScript:(FlutterMethodCall*)call result:(FlutterResult)result {
+  NSString* jsString = [call arguments];
+  if (!jsString) {
+    result([FlutterError errorWithCode:@"evaluateJavaScript_failed"
+                               message:@"JavaScript String cannot be null"
+                               details:nil]);
+    return;
+  }
+  [_webView evaluateJavaScript:jsString
+             completionHandler:^(_Nullable id evaluateResult, NSError* _Nullable error) {
+               if (error) {
+                 result([FlutterError
+                     errorWithCode:@"evaluateJavaScript_failed"
+                           message:@"Failed evaluating JavaScript"
+                           details:[NSString stringWithFormat:@"JavaScript string was: '%@'\n%@",
+                                                              jsString, error]]);
+               } else {
+                 result([NSString stringWithFormat:@"%@", evaluateResult]);
+               }
+             }];
+}
+
+- (void)onAddJavaScriptChannels:(FlutterMethodCall*)call result:(FlutterResult)result {
+  NSArray* channelNames = [call arguments];
+  NSSet* channelNamesSet = [[NSSet alloc] initWithArray:channelNames];
+  [_javaScriptChannelNames addObjectsFromArray:channelNames];
+  [self registerJavaScriptChannels:channelNamesSet
+                        controller:_webView.configuration.userContentController];
+  result(nil);
+}
+
+- (void)onRemoveJavaScriptChannels:(FlutterMethodCall*)call result:(FlutterResult)result {
+  // WkWebView does not support removing a single user script, so instead we remove all
+  // user scripts, all message handlers. And re-register channels that shouldn't be removed.
+  [_webView.configuration.userContentController removeAllUserScripts];
+  for (NSString* channelName in _javaScriptChannelNames) {
+    [_webView.configuration.userContentController removeScriptMessageHandlerForName:channelName];
+  }
+
+  NSArray* channelNamesToRemove = [call arguments];
+  for (NSString* channelName in channelNamesToRemove) {
+    [_javaScriptChannelNames removeObject:channelName];
+  }
+
+  [self registerJavaScriptChannels:_javaScriptChannelNames
+                        controller:_webView.configuration.userContentController];
+  result(nil);
+}
+
+- (void)clearCache:(FlutterResult)result {
+  if (@available(iOS 9.0, *)) {
+    NSSet* cacheDataTypes = [WKWebsiteDataStore allWebsiteDataTypes];
+    WKWebsiteDataStore* dataStore = [WKWebsiteDataStore defaultDataStore];
+    NSDate* dateFrom = [NSDate dateWithTimeIntervalSince1970:0];
+    [dataStore removeDataOfTypes:cacheDataTypes
+                   modifiedSince:dateFrom
+               completionHandler:^{
+                 result(nil);
+               }];
+  } else {
+    // support for iOS8 tracked in https://github.com/flutter/flutter/issues/27624.
+    NSLog(@"Clearing cache is not supported for Flutter WebViews prior to iOS 9.");
+  }
+}
+
+- (void)onGetTitle:(FlutterResult)result {
+  NSString* title = _webView.title;
+  result(title);
+}
+
+// Returns nil when successful, or an error message when one or more keys are unknown.
+- (NSString*)applySettings:(NSDictionary<NSString*, id>*)settings {
+  NSMutableArray<NSString*>* unknownKeys = [[NSMutableArray alloc] init];
+  for (NSString* key in settings) {
+    if ([key isEqualToString:@"jsMode"]) {
+      NSNumber* mode = settings[key];
+      [self updateJsMode:mode];
+    } else if ([key isEqualToString:@"hasNavigationDelegate"]) {
+      NSNumber* hasDartNavigationDelegate = settings[key];
+      _navigationDelegate.hasDartNavigationDelegate = [hasDartNavigationDelegate boolValue];
+    } else if ([key isEqualToString:@"debuggingEnabled"]) {
+      // no-op debugging is always enabled on iOS.
+    } else if ([key isEqualToString:@"gestureNavigationEnabled"]) {
+      NSNumber* allowsBackForwardNavigationGestures = settings[key];
+      _webView.allowsBackForwardNavigationGestures =
+          [allowsBackForwardNavigationGestures boolValue];
+    } else if ([key isEqualToString:@"userAgent"]) {
+      NSString* userAgent = settings[key];
+      [self updateUserAgent:[userAgent isEqual:[NSNull null]] ? nil : userAgent];
+    } else {
+      [unknownKeys addObject:key];
+    }
+  }
+  if ([unknownKeys count] == 0) {
+    return nil;
+  }
+  return [NSString stringWithFormat:@"webview_flutter: unknown setting keys: {%@}",
+                                    [unknownKeys componentsJoinedByString:@", "]];
+}
+
+- (void)updateJsMode:(NSNumber*)mode {
+  WKPreferences* preferences = [[_webView configuration] preferences];
+  switch ([mode integerValue]) {
+    case 0:  // disabled
+      [preferences setJavaScriptEnabled:NO];
+      break;
+    case 1:  // unrestricted
+      [preferences setJavaScriptEnabled:YES];
+      break;
+    default:
+      NSLog(@"webview_flutter: unknown JavaScript mode: %@", mode);
+  }
+}
+
+- (void)updateAutoMediaPlaybackPolicy:(NSNumber*)policy
+                      inConfiguration:(WKWebViewConfiguration*)configuration {
+  switch ([policy integerValue]) {
+    case 0:  // require_user_action_for_all_media_types
+      if (@available(iOS 10.0, *)) {
+        configuration.mediaTypesRequiringUserActionForPlayback = WKAudiovisualMediaTypeAll;
+      } else {
+        configuration.mediaPlaybackRequiresUserAction = true;
+      }
+      break;
+    case 1:  // always_allow
+      if (@available(iOS 10.0, *)) {
+        configuration.mediaTypesRequiringUserActionForPlayback = WKAudiovisualMediaTypeNone;
+      } else {
+        configuration.mediaPlaybackRequiresUserAction = false;
+      }
+      break;
+    default:
+      NSLog(@"webview_flutter: unknown auto media playback policy: %@", policy);
+  }
+}
+
+- (bool)loadRequest:(NSDictionary<NSString*, id>*)request {
+  if (!request) {
+    return false;
+  }
+
+  NSString* url = request[@"url"];
+  if ([url isKindOfClass:[NSString class]]) {
+    id headers = request[@"headers"];
+    if ([headers isKindOfClass:[NSDictionary class]]) {
+      return [self loadUrl:url withHeaders:headers];
+    } else {
+      return [self loadUrl:url];
+    }
+  }
+
+  return false;
+}
+
+- (bool)loadUrl:(NSString*)url {
+  return [self loadUrl:url withHeaders:[NSMutableDictionary dictionary]];
+}
+
+- (bool)loadUrl:(NSString*)url withHeaders:(NSDictionary<NSString*, NSString*>*)headers {
+  NSURL* nsUrl = [NSURL URLWithString:url];
+  if (!nsUrl) {
+    return false;
+  }
+  NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:nsUrl];
+  [request setAllHTTPHeaderFields:headers];
+  [_webView loadRequest:request];
+  return true;
+}
+
+- (void)registerJavaScriptChannels:(NSSet*)channelNames
+                        controller:(WKUserContentController*)userContentController {
+  for (NSString* channelName in channelNames) {
+    FLTJavaScriptChannel* channel =
+        [[FLTJavaScriptChannel alloc] initWithMethodChannel:_channel
+                                      javaScriptChannelName:channelName];
+    [userContentController addScriptMessageHandler:channel name:channelName];
+    NSString* wrapperSource = [NSString
+        stringWithFormat:@"window.%@ = webkit.messageHandlers.%@;", channelName, channelName];
+    WKUserScript* wrapperScript =
+        [[WKUserScript alloc] initWithSource:wrapperSource
+                               injectionTime:WKUserScriptInjectionTimeAtDocumentStart
+                            forMainFrameOnly:NO];
+    [userContentController addUserScript:wrapperScript];
+  }
+}
+
+- (void)updateUserAgent:(NSString*)userAgent {
+  if (@available(iOS 9.0, *)) {
+    [_webView setCustomUserAgent:userAgent];
+  } else {
+    NSLog(@"Updating UserAgent is not supported for Flutter WebViews prior to iOS 9.");
+  }
+}
+
+#pragma mark WKUIDelegate
+
+- (WKWebView*)webView:(WKWebView*)webView
+    createWebViewWithConfiguration:(WKWebViewConfiguration*)configuration
+               forNavigationAction:(WKNavigationAction*)navigationAction
+                    windowFeatures:(WKWindowFeatures*)windowFeatures {
+  if (!navigationAction.targetFrame.isMainFrame) {
+    [webView loadRequest:navigationAction.request];
+  }
+
+  return nil;
+}
+
+@end

+ 17 - 0
ios/Classes/JavaScriptChannelHandler.h

@@ -0,0 +1,17 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#import <Flutter/Flutter.h>
+#import <WebKit/WebKit.h>
+
+NS_ASSUME_NONNULL_BEGIN
+
+@interface FLTJavaScriptChannel : NSObject <WKScriptMessageHandler>
+
+- (instancetype)initWithMethodChannel:(FlutterMethodChannel*)methodChannel
+                javaScriptChannelName:(NSString*)javaScriptChannelName;
+
+@end
+
+NS_ASSUME_NONNULL_END

+ 36 - 0
ios/Classes/JavaScriptChannelHandler.m

@@ -0,0 +1,36 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#import "JavaScriptChannelHandler.h"
+
+@implementation FLTJavaScriptChannel {
+  FlutterMethodChannel* _methodChannel;
+  NSString* _javaScriptChannelName;
+}
+
+- (instancetype)initWithMethodChannel:(FlutterMethodChannel*)methodChannel
+                javaScriptChannelName:(NSString*)javaScriptChannelName {
+  self = [super init];
+  NSAssert(methodChannel != nil, @"methodChannel must not be null.");
+  NSAssert(javaScriptChannelName != nil, @"javaScriptChannelName must not be null.");
+  if (self) {
+    _methodChannel = methodChannel;
+    _javaScriptChannelName = javaScriptChannelName;
+  }
+  return self;
+}
+
+- (void)userContentController:(WKUserContentController*)userContentController
+      didReceiveScriptMessage:(WKScriptMessage*)message {
+  NSAssert(_methodChannel != nil, @"Can't send a message to an unitialized JavaScript channel.");
+  NSAssert(_javaScriptChannelName != nil,
+           @"Can't send a message to an unitialized JavaScript channel.");
+  NSDictionary* arguments = @{
+    @"channel" : _javaScriptChannelName,
+    @"message" : [NSString stringWithFormat:@"%@", message.body]
+  };
+  [_methodChannel invokeMethod:@"javascriptChannelMessage" arguments:arguments];
+}
+
+@end

+ 89 - 0
ios/Tests/FLTWebViewTests.m

@@ -0,0 +1,89 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+@import Flutter;
+@import OCMock;
+@import XCTest;
+@import webview_flutter;
+
+static bool feq(CGFloat a, CGFloat b) { return fabs(b - a) < FLT_EPSILON; }
+
+@interface FLTWebViewTests : XCTestCase
+
+@property(strong, nonatomic) NSObject<FlutterBinaryMessenger> *mockBinaryMessenger;
+
+@end
+
+@implementation FLTWebViewTests
+
+- (void)setUp {
+  [super setUp];
+  self.mockBinaryMessenger = OCMProtocolMock(@protocol(FlutterBinaryMessenger));
+}
+
+- (void)testCanInitFLTWebViewController {
+  FLTWebViewController *controller =
+      [[FLTWebViewController alloc] initWithFrame:CGRectMake(0, 0, 300, 400)
+                                   viewIdentifier:1
+                                        arguments:nil
+                                  binaryMessenger:self.mockBinaryMessenger];
+  XCTAssertNotNil(controller);
+}
+
+- (void)testCanInitFLTWebViewFactory {
+  FLTWebViewFactory *factory =
+      [[FLTWebViewFactory alloc] initWithMessenger:self.mockBinaryMessenger];
+  XCTAssertNotNil(factory);
+}
+
+- (void)webViewContentInsetBehaviorShouldBeNeverOnIOS11 {
+  if (@available(iOS 11, *)) {
+    FLTWebViewController *controller =
+        [[FLTWebViewController alloc] initWithFrame:CGRectMake(0, 0, 300, 400)
+                                     viewIdentifier:1
+                                          arguments:nil
+                                    binaryMessenger:self.mockBinaryMessenger];
+    UIView *view = controller.view;
+    XCTAssertTrue([view isKindOfClass:WKWebView.class]);
+    WKWebView *webView = (WKWebView *)view;
+    XCTAssertEqual(webView.scrollView.contentInsetAdjustmentBehavior,
+                   UIScrollViewContentInsetAdjustmentNever);
+  }
+}
+
+- (void)testWebViewScrollIndicatorAticautomaticallyAdjustsScrollIndicatorInsetsShouldbeNoOnIOS13 {
+  if (@available(iOS 13, *)) {
+    FLTWebViewController *controller =
+        [[FLTWebViewController alloc] initWithFrame:CGRectMake(0, 0, 300, 400)
+                                     viewIdentifier:1
+                                          arguments:nil
+                                    binaryMessenger:self.mockBinaryMessenger];
+    UIView *view = controller.view;
+    XCTAssertTrue([view isKindOfClass:WKWebView.class]);
+    WKWebView *webView = (WKWebView *)view;
+    XCTAssertFalse(webView.scrollView.automaticallyAdjustsScrollIndicatorInsets);
+  }
+}
+
+- (void)testContentInsetsSumAlwaysZeroAfterSetFrame {
+  FLTWKWebView *webView = [[FLTWKWebView alloc] initWithFrame:CGRectMake(0, 0, 300, 400)];
+  webView.scrollView.contentInset = UIEdgeInsetsMake(0, 0, 300, 0);
+  XCTAssertFalse(UIEdgeInsetsEqualToEdgeInsets(webView.scrollView.contentInset, UIEdgeInsetsZero));
+  webView.frame = CGRectMake(0, 0, 300, 200);
+  XCTAssertTrue(UIEdgeInsetsEqualToEdgeInsets(webView.scrollView.contentInset, UIEdgeInsetsZero));
+  XCTAssertTrue(CGRectEqualToRect(webView.frame, CGRectMake(0, 0, 300, 200)));
+
+  if (@available(iOS 11, *)) {
+    // After iOS 11, we need to make sure the contentInset compensates the adjustedContentInset.
+    UIScrollView *partialMockScrollView = OCMPartialMock(webView.scrollView);
+    UIEdgeInsets insetToAdjust = UIEdgeInsetsMake(0, 0, 300, 0);
+    OCMStub(partialMockScrollView.adjustedContentInset).andReturn(insetToAdjust);
+    XCTAssertTrue(UIEdgeInsetsEqualToEdgeInsets(webView.scrollView.contentInset, UIEdgeInsetsZero));
+    webView.frame = CGRectMake(0, 0, 300, 100);
+    XCTAssertTrue(feq(webView.scrollView.contentInset.bottom, -insetToAdjust.bottom));
+    XCTAssertTrue(CGRectEqualToRect(webView.frame, CGRectMake(0, 0, 300, 100)));
+  }
+}
+
+@end

+ 26 - 0
ios/webview_flutter.podspec

@@ -0,0 +1,26 @@
+#
+# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html
+#
+Pod::Spec.new do |s|
+  s.name             = 'webview_flutter'
+  s.version          = '0.0.1'
+  s.summary          = 'A WebView Plugin for Flutter.'
+  s.description      = <<-DESC
+A WebView Plugin for Flutter.
+                       DESC
+  s.homepage         = 'http://example.com'
+  s.license          = { :file => '../LICENSE' }
+  s.author           = { 'Your Company' => 'email@example.com' }
+  s.source           = { :path => '.' }
+  s.source_files = 'Classes/**/*'
+  s.public_header_files = 'Classes/**/*.h'
+  s.dependency 'Flutter'
+
+  s.platform = :ios, '8.0'
+  s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES', 'VALID_ARCHS[sdk=iphonesimulator*]' => 'x86_64' }
+
+  s.test_spec 'Tests' do |test_spec|
+    test_spec.source_files = 'Tests/**/*'
+    test_spec.dependency 'OCMock','3.5'
+  end
+end

+ 372 - 0
lib/platform_interface.dart

@@ -0,0 +1,372 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+import 'dart:async';
+
+import 'package:flutter/foundation.dart';
+import 'package:flutter/gestures.dart';
+import 'package:flutter/widgets.dart';
+
+import 'webview_flutter.dart';
+
+/// Interface for callbacks made by [WebViewPlatformController].
+///
+/// The webview plugin implements this class, and passes an instance to the [WebViewPlatformController].
+/// [WebViewPlatformController] is notifying this handler on events that happened on the platform's webview.
+abstract class WebViewPlatformCallbacksHandler {
+  /// Invoked by [WebViewPlatformController] when a JavaScript channel message is received.
+  void onJavaScriptChannelMessage(String channel, String message);
+
+  /// Invoked by [WebViewPlatformController] when a navigation request is pending.
+  ///
+  /// If true is returned the navigation is allowed, otherwise it is blocked.
+  FutureOr<bool> onNavigationRequest({String url, bool isForMainFrame});
+
+  /// Invoked by [WebViewPlatformController] when a page has started loading.
+  void onPageStarted(String url);
+
+  /// Invoked by [WebViewPlatformController] when a page has finished loading.
+  void onPageFinished(String url);
+}
+
+/// Interface for talking to the webview's platform implementation.
+///
+/// An instance implementing this interface is passed to the `onWebViewPlatformCreated` callback that is
+/// passed to [WebViewPlatformBuilder#onWebViewPlatformCreated].
+///
+/// Platform implementations that live in a separate package should extend this class rather than
+/// implement it as webview_flutter does not consider newly added methods to be breaking changes.
+/// Extending this class (using `extends`) ensures that the subclass will get the default
+/// implementation, while platform implementations that `implements` this interface will be broken
+/// by newly added [WebViewPlatformController] methods.
+abstract class WebViewPlatformController {
+  /// Creates a new WebViewPlatform.
+  ///
+  /// Callbacks made by the WebView will be delegated to `handler`.
+  ///
+  /// The `handler` parameter must not be null.
+  WebViewPlatformController(WebViewPlatformCallbacksHandler handler);
+
+  /// Loads the specified URL.
+  ///
+  /// If `headers` is not null and the URL is an HTTP URL, the key value paris in `headers` will
+  /// be added as key value pairs of HTTP headers for the request.
+  ///
+  /// `url` must not be null.
+  ///
+  /// Throws an ArgumentError if `url` is not a valid URL string.
+  Future<void> loadUrl(
+    String url,
+    Map<String, String> headers,
+  ) {
+    throw UnimplementedError(
+        "WebView loadUrl is not implemented on the current platform");
+  }
+
+  /// Updates the webview settings.
+  ///
+  /// Any non null field in `settings` will be set as the new setting value.
+  /// All null fields in `settings` are ignored.
+  Future<void> updateSettings(WebSettings setting) {
+    throw UnimplementedError(
+        "WebView updateSettings is not implemented on the current platform");
+  }
+
+  /// Accessor to the current URL that the WebView is displaying.
+  ///
+  /// If no URL was ever loaded, returns `null`.
+  Future<String> currentUrl() {
+    throw UnimplementedError(
+        "WebView currentUrl is not implemented on the current platform");
+  }
+
+  /// Checks whether there's a back history item.
+  Future<bool> canGoBack() {
+    throw UnimplementedError(
+        "WebView canGoBack is not implemented on the current platform");
+  }
+
+  /// Checks whether there's a forward history item.
+  Future<bool> canGoForward() {
+    throw UnimplementedError(
+        "WebView canGoForward is not implemented on the current platform");
+  }
+
+  /// Goes back in the history of this WebView.
+  ///
+  /// If there is no back history item this is a no-op.
+  Future<void> goBack() {
+    throw UnimplementedError(
+        "WebView goBack is not implemented on the current platform");
+  }
+
+  /// Goes forward in the history of this WebView.
+  ///
+  /// If there is no forward history item this is a no-op.
+  Future<void> goForward() {
+    throw UnimplementedError(
+        "WebView goForward is not implemented on the current platform");
+  }
+
+  /// Reloads the current URL.
+  Future<void> reload() {
+    throw UnimplementedError(
+        "WebView reload is not implemented on the current platform");
+  }
+
+  /// Clears all caches used by the [WebView].
+  ///
+  /// The following caches are cleared:
+  ///	1. Browser HTTP Cache.
+  ///	2. [Cache API](https://developers.google.com/web/fundamentals/instant-and-offline/web-storage/cache-api) caches.
+  ///    These are not yet supported in iOS WkWebView. Service workers tend to use this cache.
+  ///	3. Application cache.
+  ///	4. Local Storage.
+  Future<void> clearCache() {
+    throw UnimplementedError(
+        "WebView clearCache is not implemented on the current platform");
+  }
+
+  /// Evaluates a JavaScript expression in the context of the current page.
+  ///
+  /// The Future completes with an error if a JavaScript error occurred, or if the type of the
+  /// evaluated expression is not supported(e.g on iOS not all non primitive type can be evaluated).
+  Future<String> evaluateJavascript(String javascriptString) {
+    throw UnimplementedError(
+        "WebView evaluateJavascript is not implemented on the current platform");
+  }
+
+  /// Adds new JavaScript channels to the set of enabled channels.
+  ///
+  /// For each value in this list the platform's webview should make sure that a corresponding
+  /// property with a postMessage method is set on `window`. For example for a JavaScript channel
+  /// named `Foo` it should be possible for JavaScript code executing in the webview to do
+  ///
+  /// ```javascript
+  /// Foo.postMessage('hello');
+  /// ```
+  ///
+  /// See also: [CreationParams.javascriptChannelNames].
+  Future<void> addJavascriptChannels(Set<String> javascriptChannelNames) {
+    throw UnimplementedError(
+        "WebView addJavascriptChannels is not implemented on the current platform");
+  }
+
+  /// Removes JavaScript channel names from the set of enabled channels.
+  ///
+  /// This disables channels that were previously enabled by [addJavaScriptChannels] or through
+  /// [CreationParams.javascriptChannelNames].
+  Future<void> removeJavascriptChannels(Set<String> javascriptChannelNames) {
+    throw UnimplementedError(
+        "WebView removeJavascriptChannels is not implemented on the current platform");
+  }
+
+  /// Returns the title of the currently loaded page.
+  Future<String> getTitle() {
+    throw UnimplementedError(
+        "WebView getTitle is not implemented on the current platform");
+  }
+}
+
+/// A single setting for configuring a WebViewPlatform which may be absent.
+class WebSetting<T> {
+  /// Constructs an absent setting instance.
+  ///
+  /// The [isPresent] field for the instance will be false.
+  ///
+  /// Accessing [value] for an absent instance will throw.
+  WebSetting.absent()
+      : _value = null,
+        isPresent = false;
+
+  /// Constructs a setting of the given `value`.
+  ///
+  /// The [isPresent] field for the instance will be true.
+  WebSetting.of(T value)
+      : _value = value,
+        isPresent = true;
+
+  final T _value;
+
+  /// The setting's value.
+  ///
+  /// Throws if [WebSetting.isPresent] is false.
+  T get value {
+    if (!isPresent) {
+      throw StateError('Cannot access a value of an absent WebSetting');
+    }
+    assert(isPresent);
+    return _value;
+  }
+
+  /// True when this web setting instance contains a value.
+  ///
+  /// When false the [WebSetting.value] getter throws.
+  final bool isPresent;
+
+  @override
+  bool operator ==(Object other) {
+    if (other.runtimeType != runtimeType) return false;
+    final WebSetting<T> typedOther = other;
+    return typedOther.isPresent == isPresent && typedOther._value == _value;
+  }
+
+  @override
+  int get hashCode => hashValues(_value, isPresent);
+}
+
+/// Settings for configuring a WebViewPlatform.
+///
+/// Initial settings are passed as part of [CreationParams], settings updates are sent with
+/// [WebViewPlatform#updateSettings].
+///
+/// The `userAgent` parameter must not be null.
+class WebSettings {
+  /// Construct an instance with initial settings. Future setting changes can be
+  /// sent with [WebviewPlatform#updateSettings].
+  ///
+  /// The `userAgent` parameter must not be null.
+  WebSettings({
+    this.javascriptMode,
+    this.hasNavigationDelegate,
+    this.debuggingEnabled,
+    this.gestureNavigationEnabled,
+    @required this.userAgent,
+  }) : assert(userAgent != null);
+
+  /// The JavaScript execution mode to be used by the webview.
+  final JavascriptMode javascriptMode;
+
+  /// Whether the [WebView] has a [NavigationDelegate] set.
+  final bool hasNavigationDelegate;
+
+  /// Whether to enable the platform's webview content debugging tools.
+  ///
+  /// See also: [WebView.debuggingEnabled].
+  final bool debuggingEnabled;
+
+  /// The value used for the HTTP `User-Agent:` request header.
+  ///
+  /// If [userAgent.value] is null the platform's default user agent should be used.
+  ///
+  /// An absent value ([userAgent.isPresent] is false) represents no change to this setting from the
+  /// last time it was set.
+  ///
+  /// See also [WebView.userAgent].
+  final WebSetting<String> userAgent;
+
+  /// Whether to allow swipe based navigation in iOS.
+  ///
+  /// See also: [WebView.gestureNavigationEnabled]
+  final bool gestureNavigationEnabled;
+
+  @override
+  String toString() {
+    return 'WebSettings(javascriptMode: $javascriptMode, hasNavigationDelegate: $hasNavigationDelegate, debuggingEnabled: $debuggingEnabled, gestureNavigationEnabled: $gestureNavigationEnabled, userAgent: $userAgent)';
+  }
+}
+
+/// Configuration to use when creating a new [WebViewPlatformController].
+///
+/// The `autoMediaPlaybackPolicy` parameter must not be null.
+class CreationParams {
+  /// Constructs an instance to use when creating a new
+  /// [WebViewPlatformController].
+  ///
+  /// The `autoMediaPlaybackPolicy` parameter must not be null.
+  CreationParams({
+    this.initialUrl,
+    this.webSettings,
+    this.javascriptChannelNames,
+    this.userAgent,
+    this.autoMediaPlaybackPolicy =
+        AutoMediaPlaybackPolicy.require_user_action_for_all_media_types,
+  }) : assert(autoMediaPlaybackPolicy != null);
+
+  /// The initialUrl to load in the webview.
+  ///
+  /// When null the webview will be created without loading any page.
+  final String initialUrl;
+
+  /// The initial [WebSettings] for the new webview.
+  ///
+  /// This can later be updated with [WebViewPlatformController.updateSettings].
+  final WebSettings webSettings;
+
+  /// The initial set of JavaScript channels that are configured for this webview.
+  ///
+  /// For each value in this set the platform's webview should make sure that a corresponding
+  /// property with a postMessage method is set on `window`. For example for a JavaScript channel
+  /// named `Foo` it should be possible for JavaScript code executing in the webview to do
+  ///
+  /// ```javascript
+  /// Foo.postMessage('hello');
+  /// ```
+  // TODO(amirh): describe what should happen when postMessage is called once that code is migrated
+  // to PlatformWebView.
+  final Set<String> javascriptChannelNames;
+
+  /// The value used for the HTTP User-Agent: request header.
+  ///
+  /// When null the platform's webview default is used for the User-Agent header.
+  final String userAgent;
+
+  /// Which restrictions apply on automatic media playback.
+  final AutoMediaPlaybackPolicy autoMediaPlaybackPolicy;
+
+  @override
+  String toString() {
+    return '$runtimeType(initialUrl: $initialUrl, settings: $webSettings, javascriptChannelNames: $javascriptChannelNames, UserAgent: $userAgent)';
+  }
+}
+
+typedef WebViewPlatformCreatedCallback = void Function(
+    WebViewPlatformController webViewPlatformController);
+
+/// Interface for a platform implementation of a WebView.
+///
+/// [WebView.platform] controls the builder that is used by [WebView].
+/// [AndroidWebViewPlatform] and [CupertinoWebViewPlatform] are the default implementations
+/// for Android and iOS respectively.
+abstract class WebViewPlatform {
+  /// Builds a new WebView.
+  ///
+  /// Returns a Widget tree that embeds the created webview.
+  ///
+  /// `creationParams` are the initial parameters used to setup the webview.
+  ///
+  /// `webViewPlatformHandler` will be used for handling callbacks that are made by the created
+  /// [WebViewPlatformController].
+  ///
+  /// `onWebViewPlatformCreated` will be invoked after the platform specific [WebViewPlatformController]
+  /// implementation is created with the [WebViewPlatformController] instance as a parameter.
+  ///
+  /// `gestureRecognizers` specifies which gestures should be consumed by the web view.
+  /// It is possible for other gesture recognizers to be competing with the web view on pointer
+  /// events, e.g if the web view is inside a [ListView] the [ListView] will want to handle
+  /// vertical drags. The web view will claim gestures that are recognized by any of the
+  /// recognizers on this list.
+  /// When `gestureRecognizers` is empty or null, the web view will only handle pointer events for gestures that
+  /// were not claimed by any other gesture recognizer.
+  ///
+  /// `webViewPlatformHandler` must not be null.
+  Widget build({
+    BuildContext context,
+    // TODO(amirh): convert this to be the actual parameters.
+    // I'm starting without it as the PR is starting to become pretty big.
+    // I'll followup with the conversion PR.
+    CreationParams creationParams,
+    @required WebViewPlatformCallbacksHandler webViewPlatformCallbacksHandler,
+    WebViewPlatformCreatedCallback onWebViewPlatformCreated,
+    Set<Factory<OneSequenceGestureRecognizer>> gestureRecognizers,
+  });
+
+  /// Clears all cookies for all [WebView] instances.
+  ///
+  /// Returns true if cookies were present before clearing, else false.
+  Future<bool> clearCookies() {
+    throw UnimplementedError(
+        "WebView clearCookies is not implemented on the current platform");
+  }
+}

+ 63 - 0
lib/src/webview_android.dart

@@ -0,0 +1,63 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+import 'dart:async';
+
+import 'package:flutter/foundation.dart';
+import 'package:flutter/gestures.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter/widgets.dart';
+
+import '../platform_interface.dart';
+import 'webview_method_channel.dart';
+
+/// Builds an Android webview.
+///
+/// This is used as the default implementation for [WebView.platform] on Android. It uses
+/// an [AndroidView] to embed the webview in the widget hierarchy, and uses a method channel to
+/// communicate with the platform code.
+class AndroidWebView implements WebViewPlatform {
+  @override
+  Widget build({
+    BuildContext context,
+    CreationParams creationParams,
+    @required WebViewPlatformCallbacksHandler webViewPlatformCallbacksHandler,
+    WebViewPlatformCreatedCallback onWebViewPlatformCreated,
+    Set<Factory<OneSequenceGestureRecognizer>> gestureRecognizers,
+  }) {
+    assert(webViewPlatformCallbacksHandler != null);
+    return GestureDetector(
+      // We prevent text selection by intercepting the long press event.
+      // This is a temporary stop gap due to issues with text selection on Android:
+      // https://github.com/flutter/flutter/issues/24585 - the text selection
+      // dialog is not responding to touch events.
+      // https://github.com/flutter/flutter/issues/24584 - the text selection
+      // handles are not showing.
+      // TODO(amirh): remove this when the issues above are fixed.
+      onLongPress: () {},
+      excludeFromSemantics: true,
+      child: AndroidView(
+        viewType: 'plugins.flutter.io/webview',
+        onPlatformViewCreated: (int id) {
+          if (onWebViewPlatformCreated == null) {
+            return;
+          }
+          onWebViewPlatformCreated(MethodChannelWebViewPlatform(
+              id, webViewPlatformCallbacksHandler));
+        },
+        gestureRecognizers: gestureRecognizers,
+        // WebView content is not affected by the Android view's layout direction,
+        // we explicitly set it here so that the widget doesn't require an ambient
+        // directionality.
+        layoutDirection: TextDirection.rtl,
+        creationParams:
+            MethodChannelWebViewPlatform.creationParamsToMap(creationParams),
+        creationParamsCodec: const StandardMessageCodec(),
+      ),
+    );
+  }
+
+  @override
+  Future<bool> clearCookies() => MethodChannelWebViewPlatform.clearCookies();
+}

+ 47 - 0
lib/src/webview_cupertino.dart

@@ -0,0 +1,47 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+import 'dart:async';
+
+import 'package:flutter/foundation.dart';
+import 'package:flutter/gestures.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter/widgets.dart';
+
+import '../platform_interface.dart';
+import 'webview_method_channel.dart';
+
+/// Builds an iOS webview.
+///
+/// This is used as the default implementation for [WebView.platform] on iOS. It uses
+/// a [UiKitView] to embed the webview in the widget hierarchy, and uses a method channel to
+/// communicate with the platform code.
+class CupertinoWebView implements WebViewPlatform {
+  @override
+  Widget build({
+    BuildContext context,
+    CreationParams creationParams,
+    @required WebViewPlatformCallbacksHandler webViewPlatformCallbacksHandler,
+    WebViewPlatformCreatedCallback onWebViewPlatformCreated,
+    Set<Factory<OneSequenceGestureRecognizer>> gestureRecognizers,
+  }) {
+    return UiKitView(
+      viewType: 'plugins.flutter.io/webview',
+      onPlatformViewCreated: (int id) {
+        if (onWebViewPlatformCreated == null) {
+          return;
+        }
+        onWebViewPlatformCreated(
+            MethodChannelWebViewPlatform(id, webViewPlatformCallbacksHandler));
+      },
+      gestureRecognizers: gestureRecognizers,
+      creationParams:
+          MethodChannelWebViewPlatform.creationParamsToMap(creationParams),
+      creationParamsCodec: const StandardMessageCodec(),
+    );
+  }
+
+  @override
+  Future<bool> clearCookies() => MethodChannelWebViewPlatform.clearCookies();
+}

+ 160 - 0
lib/src/webview_method_channel.dart

@@ -0,0 +1,160 @@
+// Copyright 2019 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+import 'dart:async';
+
+import 'package:flutter/services.dart';
+
+import '../platform_interface.dart';
+
+/// A [WebViewPlatformController] that uses a method channel to control the webview.
+class MethodChannelWebViewPlatform implements WebViewPlatformController {
+  /// Constructs an instance that will listen for webviews broadcasting to the
+  /// given [id], using the given [WebViewPlatformCallbacksHandler].
+  MethodChannelWebViewPlatform(int id, this._platformCallbacksHandler)
+      : assert(_platformCallbacksHandler != null),
+        _channel = MethodChannel('plugins.flutter.io/webview_$id') {
+    _channel.setMethodCallHandler(_onMethodCall);
+  }
+
+  final WebViewPlatformCallbacksHandler _platformCallbacksHandler;
+
+  final MethodChannel _channel;
+
+  static const MethodChannel _cookieManagerChannel =
+      MethodChannel('plugins.flutter.io/cookie_manager');
+
+  Future<bool> _onMethodCall(MethodCall call) async {
+    switch (call.method) {
+      case 'javascriptChannelMessage':
+        final String channel = call.arguments['channel'];
+        final String message = call.arguments['message'];
+        _platformCallbacksHandler.onJavaScriptChannelMessage(channel, message);
+        return true;
+      case 'navigationRequest':
+        return await _platformCallbacksHandler.onNavigationRequest(
+          url: call.arguments['url'],
+          isForMainFrame: call.arguments['isForMainFrame'],
+        );
+      case 'onPageFinished':
+        _platformCallbacksHandler.onPageFinished(call.arguments['url']);
+        return null;
+      case 'onPageStarted':
+        _platformCallbacksHandler.onPageStarted(call.arguments['url']);
+        return null;
+    }
+    throw MissingPluginException(
+        '${call.method} was invoked but has no handler');
+  }
+
+  @override
+  Future<void> loadUrl(
+    String url,
+    Map<String, String> headers,
+  ) async {
+    assert(url != null);
+    return _channel.invokeMethod<void>('loadUrl', <String, dynamic>{
+      'url': url,
+      'headers': headers,
+    });
+  }
+
+  @override
+  Future<String> currentUrl() => _channel.invokeMethod<String>('currentUrl');
+
+  @override
+  Future<bool> canGoBack() => _channel.invokeMethod<bool>("canGoBack");
+
+  @override
+  Future<bool> canGoForward() => _channel.invokeMethod<bool>("canGoForward");
+
+  @override
+  Future<void> goBack() => _channel.invokeMethod<void>("goBack");
+
+  @override
+  Future<void> goForward() => _channel.invokeMethod<void>("goForward");
+
+  @override
+  Future<void> reload() => _channel.invokeMethod<void>("reload");
+
+  @override
+  Future<void> clearCache() => _channel.invokeMethod<void>("clearCache");
+
+  @override
+  Future<void> updateSettings(WebSettings settings) {
+    final Map<String, dynamic> updatesMap = _webSettingsToMap(settings);
+    if (updatesMap.isEmpty) {
+      return null;
+    }
+    return _channel.invokeMethod<void>('updateSettings', updatesMap);
+  }
+
+  @override
+  Future<String> evaluateJavascript(String javascriptString) {
+    return _channel.invokeMethod<String>(
+        'evaluateJavascript', javascriptString);
+  }
+
+  @override
+  Future<void> addJavascriptChannels(Set<String> javascriptChannelNames) {
+    return _channel.invokeMethod<void>(
+        'addJavascriptChannels', javascriptChannelNames.toList());
+  }
+
+  @override
+  Future<void> removeJavascriptChannels(Set<String> javascriptChannelNames) {
+    return _channel.invokeMethod<void>(
+        'removeJavascriptChannels', javascriptChannelNames.toList());
+  }
+
+  @override
+  Future<String> getTitle() => _channel.invokeMethod<String>("getTitle");
+
+  /// Method channel implementation for [WebViewPlatform.clearCookies].
+  static Future<bool> clearCookies() {
+    return _cookieManagerChannel
+        .invokeMethod<bool>('clearCookies')
+        .then<bool>((dynamic result) => result);
+  }
+
+  static Map<String, dynamic> _webSettingsToMap(WebSettings settings) {
+    final Map<String, dynamic> map = <String, dynamic>{};
+    void _addIfNonNull(String key, dynamic value) {
+      if (value == null) {
+        return;
+      }
+      map[key] = value;
+    }
+
+    void _addSettingIfPresent<T>(String key, WebSetting<T> setting) {
+      if (!setting.isPresent) {
+        return;
+      }
+      map[key] = setting.value;
+    }
+
+    _addIfNonNull('jsMode', settings.javascriptMode?.index);
+    _addIfNonNull('hasNavigationDelegate', settings.hasNavigationDelegate);
+    _addIfNonNull('debuggingEnabled', settings.debuggingEnabled);
+    _addIfNonNull(
+        'gestureNavigationEnabled', settings.gestureNavigationEnabled);
+    _addSettingIfPresent('userAgent', settings.userAgent);
+    return map;
+  }
+
+  /// Converts a [CreationParams] object to a map as expected by `platform_views` channel.
+  ///
+  /// This is used for the `creationParams` argument of the platform views created by
+  /// [AndroidWebViewBuilder] and [CupertinoWebViewBuilder].
+  static Map<String, dynamic> creationParamsToMap(
+      CreationParams creationParams) {
+    return <String, dynamic>{
+      'initialUrl': creationParams.initialUrl,
+      'settings': _webSettingsToMap(creationParams.webSettings),
+      'javascriptChannelNames': creationParams.javascriptChannelNames.toList(),
+      'userAgent': creationParams.userAgent,
+      'autoMediaPlaybackPolicy': creationParams.autoMediaPlaybackPolicy.index,
+    };
+  }
+}

+ 693 - 0
lib/webview_flutter.dart

@@ -0,0 +1,693 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+import 'dart:async';
+
+import 'package:flutter/foundation.dart';
+import 'package:flutter/gestures.dart';
+import 'package:flutter/widgets.dart';
+
+import 'platform_interface.dart';
+import 'src/webview_android.dart';
+import 'src/webview_cupertino.dart';
+
+/// Optional callback invoked when a web view is first created. [controller] is
+/// the [WebViewController] for the created web view.
+typedef void WebViewCreatedCallback(WebViewController controller);
+
+/// Describes the state of JavaScript support in a given web view.
+enum JavascriptMode {
+  /// JavaScript execution is disabled.
+  disabled,
+
+  /// JavaScript execution is not restricted.
+  unrestricted,
+}
+
+/// A message that was sent by JavaScript code running in a [WebView].
+class JavascriptMessage {
+  /// Constructs a JavaScript message object.
+  ///
+  /// The `message` parameter must not be null.
+  const JavascriptMessage(this.message) : assert(message != null);
+
+  /// The contents of the message that was sent by the JavaScript code.
+  final String message;
+}
+
+/// Callback type for handling messages sent from Javascript running in a web view.
+typedef void JavascriptMessageHandler(JavascriptMessage message);
+
+/// Information about a navigation action that is about to be executed.
+class NavigationRequest {
+  NavigationRequest._({this.url, this.isForMainFrame});
+
+  /// The URL that will be loaded if the navigation is executed.
+  final String url;
+
+  /// Whether the navigation request is to be loaded as the main frame.
+  final bool isForMainFrame;
+
+  @override
+  String toString() {
+    return '$runtimeType(url: $url, isForMainFrame: $isForMainFrame)';
+  }
+}
+
+/// A decision on how to handle a navigation request.
+enum NavigationDecision {
+  /// Prevent the navigation from taking place.
+  prevent,
+
+  /// Allow the navigation to take place.
+  navigate,
+}
+
+/// Decides how to handle a specific navigation request.
+///
+/// The returned [NavigationDecision] determines how the navigation described by
+/// `navigation` should be handled.
+///
+/// See also: [WebView.navigationDelegate].
+typedef FutureOr<NavigationDecision> NavigationDelegate(
+    NavigationRequest navigation);
+
+/// Signature for when a [WebView] has started loading a page.
+typedef void PageStartedCallback(String url);
+
+/// Signature for when a [WebView] has finished loading a page.
+typedef void PageFinishedCallback(String url);
+
+/// Specifies possible restrictions on automatic media playback.
+///
+/// This is typically used in [WebView.initialMediaPlaybackPolicy].
+// The method channel implementation is marshalling this enum to the value's index, so the order
+// is important.
+enum AutoMediaPlaybackPolicy {
+  /// Starting any kind of media playback requires a user action.
+  ///
+  /// For example: JavaScript code cannot start playing media unless the code was executed
+  /// as a result of a user action (like a touch event).
+  require_user_action_for_all_media_types,
+
+  /// Starting any kind of media playback is always allowed.
+  ///
+  /// For example: JavaScript code that's triggered when the page is loaded can start playing
+  /// video or audio.
+  always_allow,
+}
+
+final RegExp _validChannelNames = RegExp('^[a-zA-Z_][a-zA-Z0-9_]*\$');
+
+/// A named channel for receiving messaged from JavaScript code running inside a web view.
+class JavascriptChannel {
+  /// Constructs a Javascript channel.
+  ///
+  /// The parameters `name` and `onMessageReceived` must not be null.
+  JavascriptChannel({
+    @required this.name,
+    @required this.onMessageReceived,
+  })  : assert(name != null),
+        assert(onMessageReceived != null),
+        assert(_validChannelNames.hasMatch(name));
+
+  /// The channel's name.
+  ///
+  /// Passing this channel object as part of a [WebView.javascriptChannels] adds a channel object to
+  /// the Javascript window object's property named `name`.
+  ///
+  /// The name must start with a letter or underscore(_), followed by any combination of those
+  /// characters plus digits.
+  ///
+  /// Note that any JavaScript existing `window` property with this name will be overriden.
+  ///
+  /// See also [WebView.javascriptChannels] for more details on the channel registration mechanism.
+  final String name;
+
+  /// A callback that's invoked when a message is received through the channel.
+  final JavascriptMessageHandler onMessageReceived;
+}
+
+/// A web view widget for showing html content.
+class WebView extends StatefulWidget {
+  /// Creates a new web view.
+  ///
+  /// The web view can be controlled using a `WebViewController` that is passed to the
+  /// `onWebViewCreated` callback once the web view is created.
+  ///
+  /// The `javascriptMode` and `autoMediaPlaybackPolicy` parameters must not be null.
+  const WebView({
+    Key key,
+    this.onWebViewCreated,
+    this.initialUrl,
+    this.javascriptMode = JavascriptMode.disabled,
+    this.javascriptChannels,
+    this.navigationDelegate,
+    this.gestureRecognizers,
+    this.onPageStarted,
+    this.onPageFinished,
+    this.debuggingEnabled = false,
+    this.gestureNavigationEnabled = false,
+    this.userAgent,
+    this.initialMediaPlaybackPolicy =
+        AutoMediaPlaybackPolicy.require_user_action_for_all_media_types,
+  })  : assert(javascriptMode != null),
+        assert(initialMediaPlaybackPolicy != null),
+        super(key: key);
+
+  static WebViewPlatform _platform;
+
+  /// Sets a custom [WebViewPlatform].
+  ///
+  /// This property can be set to use a custom platform implementation for WebViews.
+  ///
+  /// Setting `platform` doesn't affect [WebView]s that were already created.
+  ///
+  /// The default value is [AndroidWebView] on Android and [CupertinoWebView] on iOS.
+  static set platform(WebViewPlatform platform) {
+    _platform = platform;
+  }
+
+  /// The WebView platform that's used by this WebView.
+  ///
+  /// The default value is [AndroidWebView] on Android and [CupertinoWebView] on iOS.
+  static WebViewPlatform get platform {
+    if (_platform == null) {
+      switch (defaultTargetPlatform) {
+        case TargetPlatform.android:
+          _platform = AndroidWebView();
+          break;
+        case TargetPlatform.iOS:
+          _platform = CupertinoWebView();
+          break;
+        default:
+          throw UnsupportedError(
+              "Trying to use the default webview implementation for $defaultTargetPlatform but there isn't a default one");
+      }
+    }
+    return _platform;
+  }
+
+  /// If not null invoked once the web view is created.
+  final WebViewCreatedCallback onWebViewCreated;
+
+  /// Which gestures should be consumed by the web view.
+  ///
+  /// It is possible for other gesture recognizers to be competing with the web view on pointer
+  /// events, e.g if the web view is inside a [ListView] the [ListView] will want to handle
+  /// vertical drags. The web view will claim gestures that are recognized by any of the
+  /// recognizers on this list.
+  ///
+  /// When this set is empty or null, the web view will only handle pointer events for gestures that
+  /// were not claimed by any other gesture recognizer.
+  final Set<Factory<OneSequenceGestureRecognizer>> gestureRecognizers;
+
+  /// The initial URL to load.
+  final String initialUrl;
+
+  /// Whether Javascript execution is enabled.
+  final JavascriptMode javascriptMode;
+
+  /// The set of [JavascriptChannel]s available to JavaScript code running in the web view.
+  ///
+  /// For each [JavascriptChannel] in the set, a channel object is made available for the
+  /// JavaScript code in a window property named [JavascriptChannel.name].
+  /// The JavaScript code can then call `postMessage` on that object to send a message that will be
+  /// passed to [JavascriptChannel.onMessageReceived].
+  ///
+  /// For example for the following JavascriptChannel:
+  ///
+  /// ```dart
+  /// JavascriptChannel(name: 'Print', onMessageReceived: (JavascriptMessage message) { print(message.message); });
+  /// ```
+  ///
+  /// JavaScript code can call:
+  ///
+  /// ```javascript
+  /// Print.postMessage('Hello');
+  /// ```
+  ///
+  /// To asynchronously invoke the message handler which will print the message to standard output.
+  ///
+  /// Adding a new JavaScript channel only takes affect after the next page is loaded.
+  ///
+  /// Set values must not be null. A [JavascriptChannel.name] cannot be the same for multiple
+  /// channels in the list.
+  ///
+  /// A null value is equivalent to an empty set.
+  final Set<JavascriptChannel> javascriptChannels;
+
+  /// A delegate function that decides how to handle navigation actions.
+  ///
+  /// When a navigation is initiated by the WebView (e.g when a user clicks a link)
+  /// this delegate is called and has to decide how to proceed with the navigation.
+  ///
+  /// See [NavigationDecision] for possible decisions the delegate can take.
+  ///
+  /// When null all navigation actions are allowed.
+  ///
+  /// Caveats on Android:
+  ///
+  ///   * Navigation actions targeted to the main frame can be intercepted,
+  ///     navigation actions targeted to subframes are allowed regardless of the value
+  ///     returned by this delegate.
+  ///   * Setting a navigationDelegate makes the WebView treat all navigations as if they were
+  ///     triggered by a user gesture, this disables some of Chromium's security mechanisms.
+  ///     A navigationDelegate should only be set when loading trusted content.
+  ///   * On Android WebView versions earlier than 67(most devices running at least Android L+ should have
+  ///     a later version):
+  ///     * When a navigationDelegate is set pages with frames are not properly handled by the
+  ///       webview, and frames will be opened in the main frame.
+  ///     * When a navigationDelegate is set HTTP requests do not include the HTTP referer header.
+  final NavigationDelegate navigationDelegate;
+
+  /// Invoked when a page starts loading.
+  final PageStartedCallback onPageStarted;
+
+  /// Invoked when a page has finished loading.
+  ///
+  /// This is invoked only for the main frame.
+  ///
+  /// When [onPageFinished] is invoked on Android, the page being rendered may
+  /// not be updated yet.
+  ///
+  /// When invoked on iOS or Android, any Javascript code that is embedded
+  /// directly in the HTML has been loaded and code injected with
+  /// [WebViewController.evaluateJavascript] can assume this.
+  final PageFinishedCallback onPageFinished;
+
+  /// Controls whether WebView debugging is enabled.
+  ///
+  /// Setting this to true enables [WebView debugging on Android](https://developers.google.com/web/tools/chrome-devtools/remote-debugging/).
+  ///
+  /// WebView debugging is enabled by default in dev builds on iOS.
+  ///
+  /// To debug WebViews on iOS:
+  /// - Enable developer options (Open Safari, go to Preferences -> Advanced and make sure "Show Develop Menu in Menubar" is on.)
+  /// - From the Menu-bar (of Safari) select Develop -> iPhone Simulator -> <your webview page>
+  ///
+  /// By default `debuggingEnabled` is false.
+  final bool debuggingEnabled;
+
+  /// The value used for the HTTP User-Agent: request header.
+  /// A Boolean value indicating whether horizontal swipe gestures will trigger back-forward list navigations.
+  ///
+  /// This only works on iOS.
+  ///
+  /// By default `gestureNavigationEnabled` is false.
+  final bool gestureNavigationEnabled;
+
+  ///
+  /// When null the platform's webview default is used for the User-Agent header.
+  ///
+  /// When the [WebView] is rebuilt with a different `userAgent`, the page reloads and the request uses the new User Agent.
+  ///
+  /// When [WebViewController.goBack] is called after changing `userAgent` the previous `userAgent` value is used until the page is reloaded.
+  ///
+  /// This field is ignored on iOS versions prior to 9 as the platform does not support a custom
+  /// user agent.
+  ///
+  /// By default `userAgent` is null.
+  final String userAgent;
+
+  /// Which restrictions apply on automatic media playback.
+  ///
+  /// This initial value is applied to the platform's webview upon creation. Any following
+  /// changes to this parameter are ignored (as long as the state of the [WebView] is preserved).
+  ///
+  /// The default policy is [AutoMediaPlaybackPolicy.require_user_action_for_all_media_types].
+  final AutoMediaPlaybackPolicy initialMediaPlaybackPolicy;
+
+  @override
+  State<StatefulWidget> createState() => _WebViewState();
+}
+
+class _WebViewState extends State<WebView> {
+  final Completer<WebViewController> _controller =
+      Completer<WebViewController>();
+
+  _PlatformCallbacksHandler _platformCallbacksHandler;
+
+  @override
+  Widget build(BuildContext context) {
+    return WebView.platform.build(
+      context: context,
+      onWebViewPlatformCreated: _onWebViewPlatformCreated,
+      webViewPlatformCallbacksHandler: _platformCallbacksHandler,
+      gestureRecognizers: widget.gestureRecognizers,
+      creationParams: _creationParamsfromWidget(widget),
+    );
+  }
+
+  @override
+  void initState() {
+    super.initState();
+    _assertJavascriptChannelNamesAreUnique();
+    _platformCallbacksHandler = _PlatformCallbacksHandler(widget);
+  }
+
+  @override
+  void didUpdateWidget(WebView oldWidget) {
+    super.didUpdateWidget(oldWidget);
+    _assertJavascriptChannelNamesAreUnique();
+    _controller.future.then((WebViewController controller) {
+      _platformCallbacksHandler._widget = widget;
+      controller._updateWidget(widget);
+    });
+  }
+
+  void _onWebViewPlatformCreated(WebViewPlatformController webViewPlatform) {
+    final WebViewController controller =
+        WebViewController._(widget, webViewPlatform, _platformCallbacksHandler);
+    _controller.complete(controller);
+    if (widget.onWebViewCreated != null) {
+      widget.onWebViewCreated(controller);
+    }
+  }
+
+  void _assertJavascriptChannelNamesAreUnique() {
+    if (widget.javascriptChannels == null ||
+        widget.javascriptChannels.isEmpty) {
+      return;
+    }
+    assert(_extractChannelNames(widget.javascriptChannels).length ==
+        widget.javascriptChannels.length);
+  }
+}
+
+CreationParams _creationParamsfromWidget(WebView widget) {
+  return CreationParams(
+    initialUrl: widget.initialUrl,
+    webSettings: _webSettingsFromWidget(widget),
+    javascriptChannelNames: _extractChannelNames(widget.javascriptChannels),
+    userAgent: widget.userAgent,
+    autoMediaPlaybackPolicy: widget.initialMediaPlaybackPolicy,
+  );
+}
+
+WebSettings _webSettingsFromWidget(WebView widget) {
+  return WebSettings(
+    javascriptMode: widget.javascriptMode,
+    hasNavigationDelegate: widget.navigationDelegate != null,
+    debuggingEnabled: widget.debuggingEnabled,
+    gestureNavigationEnabled: widget.gestureNavigationEnabled,
+    userAgent: WebSetting<String>.of(widget.userAgent),
+  );
+}
+
+// This method assumes that no fields in `currentValue` are null.
+WebSettings _clearUnchangedWebSettings(
+    WebSettings currentValue, WebSettings newValue) {
+  assert(currentValue.javascriptMode != null);
+  assert(currentValue.hasNavigationDelegate != null);
+  assert(currentValue.debuggingEnabled != null);
+  assert(currentValue.userAgent.isPresent);
+  assert(newValue.javascriptMode != null);
+  assert(newValue.hasNavigationDelegate != null);
+  assert(newValue.debuggingEnabled != null);
+  assert(newValue.userAgent.isPresent);
+
+  JavascriptMode javascriptMode;
+  bool hasNavigationDelegate;
+  bool debuggingEnabled;
+  WebSetting<String> userAgent = WebSetting<String>.absent();
+  if (currentValue.javascriptMode != newValue.javascriptMode) {
+    javascriptMode = newValue.javascriptMode;
+  }
+  if (currentValue.hasNavigationDelegate != newValue.hasNavigationDelegate) {
+    hasNavigationDelegate = newValue.hasNavigationDelegate;
+  }
+  if (currentValue.debuggingEnabled != newValue.debuggingEnabled) {
+    debuggingEnabled = newValue.debuggingEnabled;
+  }
+  if (currentValue.userAgent != newValue.userAgent) {
+    userAgent = newValue.userAgent;
+  }
+
+  return WebSettings(
+    javascriptMode: javascriptMode,
+    hasNavigationDelegate: hasNavigationDelegate,
+    debuggingEnabled: debuggingEnabled,
+    userAgent: userAgent,
+  );
+}
+
+Set<String> _extractChannelNames(Set<JavascriptChannel> channels) {
+  final Set<String> channelNames = channels == null
+      // TODO(iskakaushik): Remove this when collection literals makes it to stable.
+      // ignore: prefer_collection_literals
+      ? Set<String>()
+      : channels.map((JavascriptChannel channel) => channel.name).toSet();
+  return channelNames;
+}
+
+class _PlatformCallbacksHandler implements WebViewPlatformCallbacksHandler {
+  _PlatformCallbacksHandler(this._widget) {
+    _updateJavascriptChannelsFromSet(_widget.javascriptChannels);
+  }
+
+  WebView _widget;
+
+  // Maps a channel name to a channel.
+  final Map<String, JavascriptChannel> _javascriptChannels =
+      <String, JavascriptChannel>{};
+
+  @override
+  void onJavaScriptChannelMessage(String channel, String message) {
+    _javascriptChannels[channel].onMessageReceived(JavascriptMessage(message));
+  }
+
+  @override
+  FutureOr<bool> onNavigationRequest({String url, bool isForMainFrame}) async {
+    final NavigationRequest request =
+        NavigationRequest._(url: url, isForMainFrame: isForMainFrame);
+    final bool allowNavigation = _widget.navigationDelegate == null ||
+        await _widget.navigationDelegate(request) ==
+            NavigationDecision.navigate;
+    return allowNavigation;
+  }
+
+  @override
+  void onPageStarted(String url) {
+    if (_widget.onPageStarted != null) {
+      _widget.onPageStarted(url);
+    }
+  }
+
+  @override
+  void onPageFinished(String url) {
+    if (_widget.onPageFinished != null) {
+      _widget.onPageFinished(url);
+    }
+  }
+
+  void _updateJavascriptChannelsFromSet(Set<JavascriptChannel> channels) {
+    _javascriptChannels.clear();
+    if (channels == null) {
+      return;
+    }
+    for (JavascriptChannel channel in channels) {
+      _javascriptChannels[channel.name] = channel;
+    }
+  }
+}
+
+/// Controls a [WebView].
+///
+/// A [WebViewController] instance can be obtained by setting the [WebView.onWebViewCreated]
+/// callback for a [WebView] widget.
+class WebViewController {
+  WebViewController._(
+    this._widget,
+    this._webViewPlatformController,
+    this._platformCallbacksHandler,
+  ) : assert(_webViewPlatformController != null) {
+    _settings = _webSettingsFromWidget(_widget);
+  }
+
+  final WebViewPlatformController _webViewPlatformController;
+
+  final _PlatformCallbacksHandler _platformCallbacksHandler;
+
+  WebSettings _settings;
+
+  WebView _widget;
+
+  /// Loads the specified URL.
+  ///
+  /// If `headers` is not null and the URL is an HTTP URL, the key value paris in `headers` will
+  /// be added as key value pairs of HTTP headers for the request.
+  ///
+  /// `url` must not be null.
+  ///
+  /// Throws an ArgumentError if `url` is not a valid URL string.
+  Future<void> loadUrl(
+    String url, {
+    Map<String, String> headers,
+  }) async {
+    assert(url != null);
+    _validateUrlString(url);
+    return _webViewPlatformController.loadUrl(url, headers);
+  }
+
+  /// Accessor to the current URL that the WebView is displaying.
+  ///
+  /// If [WebView.initialUrl] was never specified, returns `null`.
+  /// Note that this operation is asynchronous, and it is possible that the
+  /// current URL changes again by the time this function returns (in other
+  /// words, by the time this future completes, the WebView may be displaying a
+  /// different URL).
+  Future<String> currentUrl() {
+    return _webViewPlatformController.currentUrl();
+  }
+
+  /// Checks whether there's a back history item.
+  ///
+  /// Note that this operation is asynchronous, and it is possible that the "canGoBack" state has
+  /// changed by the time the future completed.
+  Future<bool> canGoBack() {
+    return _webViewPlatformController.canGoBack();
+  }
+
+  /// Checks whether there's a forward history item.
+  ///
+  /// Note that this operation is asynchronous, and it is possible that the "canGoForward" state has
+  /// changed by the time the future completed.
+  Future<bool> canGoForward() {
+    return _webViewPlatformController.canGoForward();
+  }
+
+  /// Goes back in the history of this WebView.
+  ///
+  /// If there is no back history item this is a no-op.
+  Future<void> goBack() {
+    return _webViewPlatformController.goBack();
+  }
+
+  /// Goes forward in the history of this WebView.
+  ///
+  /// If there is no forward history item this is a no-op.
+  Future<void> goForward() {
+    return _webViewPlatformController.goForward();
+  }
+
+  /// Reloads the current URL.
+  Future<void> reload() {
+    return _webViewPlatformController.reload();
+  }
+
+  /// Clears all caches used by the [WebView].
+  ///
+  /// The following caches are cleared:
+  ///	1. Browser HTTP Cache.
+  ///	2. [Cache API](https://developers.google.com/web/fundamentals/instant-and-offline/web-storage/cache-api) caches.
+  ///    These are not yet supported in iOS WkWebView. Service workers tend to use this cache.
+  ///	3. Application cache.
+  ///	4. Local Storage.
+  ///
+  /// Note: Calling this method also triggers a reload.
+  Future<void> clearCache() async {
+    await _webViewPlatformController.clearCache();
+    return reload();
+  }
+
+  Future<void> _updateWidget(WebView widget) async {
+    _widget = widget;
+    await _updateSettings(_webSettingsFromWidget(widget));
+    await _updateJavascriptChannels(widget.javascriptChannels);
+  }
+
+  Future<void> _updateSettings(WebSettings newSettings) {
+    final WebSettings update =
+        _clearUnchangedWebSettings(_settings, newSettings);
+    _settings = newSettings;
+    return _webViewPlatformController.updateSettings(update);
+  }
+
+  Future<void> _updateJavascriptChannels(
+      Set<JavascriptChannel> newChannels) async {
+    final Set<String> currentChannels =
+        _platformCallbacksHandler._javascriptChannels.keys.toSet();
+    final Set<String> newChannelNames = _extractChannelNames(newChannels);
+    final Set<String> channelsToAdd =
+        newChannelNames.difference(currentChannels);
+    final Set<String> channelsToRemove =
+        currentChannels.difference(newChannelNames);
+    if (channelsToRemove.isNotEmpty) {
+      await _webViewPlatformController
+          .removeJavascriptChannels(channelsToRemove);
+    }
+    if (channelsToAdd.isNotEmpty) {
+      await _webViewPlatformController.addJavascriptChannels(channelsToAdd);
+    }
+    _platformCallbacksHandler._updateJavascriptChannelsFromSet(newChannels);
+  }
+
+  /// Evaluates a JavaScript expression in the context of the current page.
+  ///
+  /// On Android returns the evaluation result as a JSON formatted string.
+  ///
+  /// On iOS depending on the value type the return value would be one of:
+  ///
+  ///  - For primitive JavaScript types: the value string formatted (e.g JavaScript 100 returns '100').
+  ///  - For JavaScript arrays of supported types: a string formatted NSArray(e.g '(1,2,3), note that the string for NSArray is formatted and might contain newlines and extra spaces.').
+  ///  - Other non-primitive types are not supported on iOS and will complete the Future with an error.
+  ///
+  /// The Future completes with an error if a JavaScript error occurred, or on iOS, if the type of the
+  /// evaluated expression is not supported as described above.
+  ///
+  /// When evaluating Javascript in a [WebView], it is best practice to wait for
+  /// the [WebView.onPageFinished] callback. This guarantees all the Javascript
+  /// embedded in the main frame HTML has been loaded.
+  Future<String> evaluateJavascript(String javascriptString) {
+    if (_settings.javascriptMode == JavascriptMode.disabled) {
+      return Future<String>.error(FlutterError(
+          'JavaScript mode must be enabled/unrestricted when calling evaluateJavascript.'));
+    }
+    if (javascriptString == null) {
+      return Future<String>.error(
+          ArgumentError('The argument javascriptString must not be null.'));
+    }
+    // TODO(amirh): remove this on when the invokeMethod update makes it to stable Flutter.
+    // https://github.com/flutter/flutter/issues/26431
+    // ignore: strong_mode_implicit_dynamic_method
+    return _webViewPlatformController.evaluateJavascript(javascriptString);
+  }
+
+  /// Returns the title of the currently loaded page.
+  Future<String> getTitle() {
+    return _webViewPlatformController.getTitle();
+  }
+}
+
+/// Manages cookies pertaining to all [WebView]s.
+class CookieManager {
+  /// Creates a [CookieManager] -- returns the instance if it's already been called.
+  factory CookieManager() {
+    return _instance ??= CookieManager._();
+  }
+
+  CookieManager._();
+
+  static CookieManager _instance;
+
+  /// Clears all cookies for all [WebView] instances.
+  ///
+  /// This is a no op on iOS version smaller than 9.
+  ///
+  /// Returns true if cookies were present before clearing, else false.
+  Future<bool> clearCookies() => WebView.platform.clearCookies();
+}
+
+// Throws an ArgumentError if `url` is not a valid URL string.
+void _validateUrlString(String url) {
+  try {
+    final Uri uri = Uri.parse(url);
+    if (uri.scheme.isEmpty) {
+      throw ArgumentError('Missing scheme in URL string: "$url"');
+    }
+  } on FormatException catch (e) {
+    throw ArgumentError(e);
+  }
+}

+ 28 - 0
pubspec.yaml

@@ -0,0 +1,28 @@
+name: webview_flutter
+description: A Flutter plugin that provides a WebView widget on Android and iOS.
+version: 0.3.19+9
+homepage: https://github.com/flutter/plugins/tree/master/packages/webview_flutter
+
+environment:
+  sdk: ">=2.0.0-dev.68.0 <3.0.0"
+  flutter: ">=1.12.13+hotfix.5"
+
+dependencies:
+  flutter:
+    sdk: flutter
+
+dev_dependencies:
+  flutter_test:
+    sdk: flutter
+  flutter_driver:
+    sdk: flutter
+  pedantic: ^1.8.0
+
+flutter:
+  plugin:
+    platforms:
+      android:
+        package: io.flutter.plugins.webviewflutter
+        pluginClass: WebViewFlutterPlugin
+      ios:
+        pluginClass: FLTWebViewFlutterPlugin

+ 1211 - 0
test/webview_flutter_test.dart

@@ -0,0 +1,1211 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+import 'dart:math';
+import 'dart:typed_data';
+
+import 'package:flutter/services.dart';
+import 'package:flutter/src/foundation/basic_types.dart';
+import 'package:flutter/src/gestures/recognizer.dart';
+import 'package:flutter/widgets.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:webview_flutter/platform_interface.dart';
+import 'package:webview_flutter/webview_flutter.dart';
+
+typedef void VoidCallback();
+
+void main() {
+  TestWidgetsFlutterBinding.ensureInitialized();
+
+  final _FakePlatformViewsController fakePlatformViewsController =
+      _FakePlatformViewsController();
+
+  final _FakeCookieManager _fakeCookieManager = _FakeCookieManager();
+
+  setUpAll(() {
+    SystemChannels.platform_views.setMockMethodCallHandler(
+        fakePlatformViewsController.fakePlatformViewsMethodHandler);
+    SystemChannels.platform
+        .setMockMethodCallHandler(_fakeCookieManager.onMethodCall);
+  });
+
+  setUp(() {
+    fakePlatformViewsController.reset();
+    _fakeCookieManager.reset();
+  });
+
+  testWidgets('Create WebView', (WidgetTester tester) async {
+    await tester.pumpWidget(const WebView());
+  });
+
+  testWidgets('Initial url', (WidgetTester tester) async {
+    WebViewController controller;
+    await tester.pumpWidget(
+      WebView(
+        initialUrl: 'https://youtube.com',
+        onWebViewCreated: (WebViewController webViewController) {
+          controller = webViewController;
+        },
+      ),
+    );
+
+    expect(await controller.currentUrl(), 'https://youtube.com');
+  });
+
+  testWidgets('Javascript mode', (WidgetTester tester) async {
+    await tester.pumpWidget(const WebView(
+      initialUrl: 'https://youtube.com',
+      javascriptMode: JavascriptMode.unrestricted,
+    ));
+
+    final FakePlatformWebView platformWebView =
+        fakePlatformViewsController.lastCreatedView;
+
+    expect(platformWebView.javascriptMode, JavascriptMode.unrestricted);
+
+    await tester.pumpWidget(const WebView(
+      initialUrl: 'https://youtube.com',
+      javascriptMode: JavascriptMode.disabled,
+    ));
+    expect(platformWebView.javascriptMode, JavascriptMode.disabled);
+  });
+
+  testWidgets('Load url', (WidgetTester tester) async {
+    WebViewController controller;
+    await tester.pumpWidget(
+      WebView(
+        onWebViewCreated: (WebViewController webViewController) {
+          controller = webViewController;
+        },
+      ),
+    );
+
+    expect(controller, isNotNull);
+
+    await controller.loadUrl('https://flutter.io');
+
+    expect(await controller.currentUrl(), 'https://flutter.io');
+  });
+
+  testWidgets('Invalid urls', (WidgetTester tester) async {
+    WebViewController controller;
+    await tester.pumpWidget(
+      WebView(
+        onWebViewCreated: (WebViewController webViewController) {
+          controller = webViewController;
+        },
+      ),
+    );
+
+    expect(controller, isNotNull);
+
+    expect(() => controller.loadUrl(null), throwsA(anything));
+    expect(await controller.currentUrl(), isNull);
+
+    expect(() => controller.loadUrl(''), throwsA(anything));
+    expect(await controller.currentUrl(), isNull);
+
+    // Missing schema.
+    expect(() => controller.loadUrl('flutter.io'), throwsA(anything));
+    expect(await controller.currentUrl(), isNull);
+  });
+
+  testWidgets('Headers in loadUrl', (WidgetTester tester) async {
+    WebViewController controller;
+    await tester.pumpWidget(
+      WebView(
+        onWebViewCreated: (WebViewController webViewController) {
+          controller = webViewController;
+        },
+      ),
+    );
+
+    expect(controller, isNotNull);
+
+    final Map<String, String> headers = <String, String>{
+      'CACHE-CONTROL': 'ABC'
+    };
+    await controller.loadUrl('https://flutter.io', headers: headers);
+    expect(await controller.currentUrl(), equals('https://flutter.io'));
+  });
+
+  testWidgets("Can't go back before loading a page",
+      (WidgetTester tester) async {
+    WebViewController controller;
+    await tester.pumpWidget(
+      WebView(
+        onWebViewCreated: (WebViewController webViewController) {
+          controller = webViewController;
+        },
+      ),
+    );
+
+    expect(controller, isNotNull);
+
+    final bool canGoBackNoPageLoaded = await controller.canGoBack();
+
+    expect(canGoBackNoPageLoaded, false);
+  });
+
+  testWidgets("Clear Cache", (WidgetTester tester) async {
+    WebViewController controller;
+    await tester.pumpWidget(
+      WebView(
+        onWebViewCreated: (WebViewController webViewController) {
+          controller = webViewController;
+        },
+      ),
+    );
+
+    expect(controller, isNotNull);
+    expect(fakePlatformViewsController.lastCreatedView.hasCache, true);
+
+    await controller.clearCache();
+
+    expect(fakePlatformViewsController.lastCreatedView.hasCache, false);
+  });
+
+  testWidgets("Can't go back with no history", (WidgetTester tester) async {
+    WebViewController controller;
+    await tester.pumpWidget(
+      WebView(
+        initialUrl: 'https://flutter.io',
+        onWebViewCreated: (WebViewController webViewController) {
+          controller = webViewController;
+        },
+      ),
+    );
+
+    expect(controller, isNotNull);
+    final bool canGoBackFirstPageLoaded = await controller.canGoBack();
+
+    expect(canGoBackFirstPageLoaded, false);
+  });
+
+  testWidgets('Can go back', (WidgetTester tester) async {
+    WebViewController controller;
+    await tester.pumpWidget(
+      WebView(
+        initialUrl: 'https://flutter.io',
+        onWebViewCreated: (WebViewController webViewController) {
+          controller = webViewController;
+        },
+      ),
+    );
+
+    expect(controller, isNotNull);
+
+    await controller.loadUrl('https://www.google.com');
+    final bool canGoBackSecondPageLoaded = await controller.canGoBack();
+
+    expect(canGoBackSecondPageLoaded, true);
+  });
+
+  testWidgets("Can't go forward before loading a page",
+      (WidgetTester tester) async {
+    WebViewController controller;
+    await tester.pumpWidget(
+      WebView(
+        onWebViewCreated: (WebViewController webViewController) {
+          controller = webViewController;
+        },
+      ),
+    );
+
+    expect(controller, isNotNull);
+
+    final bool canGoForwardNoPageLoaded = await controller.canGoForward();
+
+    expect(canGoForwardNoPageLoaded, false);
+  });
+
+  testWidgets("Can't go forward with no history", (WidgetTester tester) async {
+    WebViewController controller;
+    await tester.pumpWidget(
+      WebView(
+        initialUrl: 'https://flutter.io',
+        onWebViewCreated: (WebViewController webViewController) {
+          controller = webViewController;
+        },
+      ),
+    );
+
+    expect(controller, isNotNull);
+    final bool canGoForwardFirstPageLoaded = await controller.canGoForward();
+
+    expect(canGoForwardFirstPageLoaded, false);
+  });
+
+  testWidgets('Can go forward', (WidgetTester tester) async {
+    WebViewController controller;
+    await tester.pumpWidget(
+      WebView(
+        initialUrl: 'https://flutter.io',
+        onWebViewCreated: (WebViewController webViewController) {
+          controller = webViewController;
+        },
+      ),
+    );
+
+    expect(controller, isNotNull);
+
+    await controller.loadUrl('https://youtube.com');
+    await controller.goBack();
+    final bool canGoForwardFirstPageBacked = await controller.canGoForward();
+
+    expect(canGoForwardFirstPageBacked, true);
+  });
+
+  testWidgets('Go back', (WidgetTester tester) async {
+    WebViewController controller;
+    await tester.pumpWidget(
+      WebView(
+        initialUrl: 'https://youtube.com',
+        onWebViewCreated: (WebViewController webViewController) {
+          controller = webViewController;
+        },
+      ),
+    );
+
+    expect(controller, isNotNull);
+
+    expect(await controller.currentUrl(), 'https://youtube.com');
+
+    await controller.loadUrl('https://flutter.io');
+
+    expect(await controller.currentUrl(), 'https://flutter.io');
+
+    await controller.goBack();
+
+    expect(await controller.currentUrl(), 'https://youtube.com');
+  });
+
+  testWidgets('Go forward', (WidgetTester tester) async {
+    WebViewController controller;
+    await tester.pumpWidget(
+      WebView(
+        initialUrl: 'https://youtube.com',
+        onWebViewCreated: (WebViewController webViewController) {
+          controller = webViewController;
+        },
+      ),
+    );
+
+    expect(controller, isNotNull);
+
+    expect(await controller.currentUrl(), 'https://youtube.com');
+
+    await controller.loadUrl('https://flutter.io');
+
+    expect(await controller.currentUrl(), 'https://flutter.io');
+
+    await controller.goBack();
+
+    expect(await controller.currentUrl(), 'https://youtube.com');
+
+    await controller.goForward();
+
+    expect(await controller.currentUrl(), 'https://flutter.io');
+  });
+
+  testWidgets('Current URL', (WidgetTester tester) async {
+    WebViewController controller;
+    await tester.pumpWidget(
+      WebView(
+        onWebViewCreated: (WebViewController webViewController) {
+          controller = webViewController;
+        },
+      ),
+    );
+
+    expect(controller, isNotNull);
+
+    // Test a WebView without an explicitly set first URL.
+    expect(await controller.currentUrl(), isNull);
+
+    await controller.loadUrl('https://youtube.com');
+    expect(await controller.currentUrl(), 'https://youtube.com');
+
+    await controller.loadUrl('https://flutter.io');
+    expect(await controller.currentUrl(), 'https://flutter.io');
+
+    await controller.goBack();
+    expect(await controller.currentUrl(), 'https://youtube.com');
+  });
+
+  testWidgets('Reload url', (WidgetTester tester) async {
+    WebViewController controller;
+    await tester.pumpWidget(
+      WebView(
+        initialUrl: 'https://flutter.io',
+        onWebViewCreated: (WebViewController webViewController) {
+          controller = webViewController;
+        },
+      ),
+    );
+
+    final FakePlatformWebView platformWebView =
+        fakePlatformViewsController.lastCreatedView;
+
+    expect(platformWebView.currentUrl, 'https://flutter.io');
+    expect(platformWebView.amountOfReloadsOnCurrentUrl, 0);
+
+    await controller.reload();
+
+    expect(platformWebView.currentUrl, 'https://flutter.io');
+    expect(platformWebView.amountOfReloadsOnCurrentUrl, 1);
+
+    await controller.loadUrl('https://youtube.com');
+
+    expect(platformWebView.amountOfReloadsOnCurrentUrl, 0);
+  });
+
+  testWidgets('evaluate Javascript', (WidgetTester tester) async {
+    WebViewController controller;
+    await tester.pumpWidget(
+      WebView(
+        initialUrl: 'https://flutter.io',
+        javascriptMode: JavascriptMode.unrestricted,
+        onWebViewCreated: (WebViewController webViewController) {
+          controller = webViewController;
+        },
+      ),
+    );
+    expect(
+        await controller.evaluateJavascript("fake js string"), "fake js string",
+        reason: 'should get the argument');
+    expect(
+      () => controller.evaluateJavascript(null),
+      throwsA(anything),
+    );
+  });
+
+  testWidgets('evaluate Javascript with JavascriptMode disabled',
+      (WidgetTester tester) async {
+    WebViewController controller;
+    await tester.pumpWidget(
+      WebView(
+        initialUrl: 'https://flutter.io',
+        javascriptMode: JavascriptMode.disabled,
+        onWebViewCreated: (WebViewController webViewController) {
+          controller = webViewController;
+        },
+      ),
+    );
+    expect(
+      () => controller.evaluateJavascript('fake js string'),
+      throwsA(anything),
+    );
+    expect(
+      () => controller.evaluateJavascript(null),
+      throwsA(anything),
+    );
+  });
+
+  testWidgets('Cookies can be cleared once', (WidgetTester tester) async {
+    await tester.pumpWidget(
+      const WebView(
+        initialUrl: 'https://flutter.io',
+      ),
+    );
+    final CookieManager cookieManager = CookieManager();
+    final bool hasCookies = await cookieManager.clearCookies();
+    expect(hasCookies, true);
+  });
+
+  testWidgets('Second cookie clear does not have cookies',
+      (WidgetTester tester) async {
+    await tester.pumpWidget(
+      const WebView(
+        initialUrl: 'https://flutter.io',
+      ),
+    );
+    final CookieManager cookieManager = CookieManager();
+    final bool hasCookies = await cookieManager.clearCookies();
+    expect(hasCookies, true);
+    final bool hasCookiesSecond = await cookieManager.clearCookies();
+    expect(hasCookiesSecond, false);
+  });
+
+  testWidgets('Initial JavaScript channels', (WidgetTester tester) async {
+    await tester.pumpWidget(
+      WebView(
+        initialUrl: 'https://youtube.com',
+        // TODO(iskakaushik): Remove this when collection literals makes it to stable.
+        // ignore: prefer_collection_literals
+        javascriptChannels: <JavascriptChannel>[
+          JavascriptChannel(
+              name: 'Tts', onMessageReceived: (JavascriptMessage msg) {}),
+          JavascriptChannel(
+              name: 'Alarm', onMessageReceived: (JavascriptMessage msg) {}),
+        ].toSet(),
+      ),
+    );
+
+    final FakePlatformWebView platformWebView =
+        fakePlatformViewsController.lastCreatedView;
+
+    expect(platformWebView.javascriptChannelNames,
+        unorderedEquals(<String>['Tts', 'Alarm']));
+  });
+
+  test('Only valid JavaScript channel names are allowed', () {
+    final JavascriptMessageHandler noOp = (JavascriptMessage msg) {};
+    JavascriptChannel(name: 'Tts1', onMessageReceived: noOp);
+    JavascriptChannel(name: '_Alarm', onMessageReceived: noOp);
+    JavascriptChannel(name: 'foo_bar_', onMessageReceived: noOp);
+
+    VoidCallback createChannel(String name) {
+      return () {
+        JavascriptChannel(name: name, onMessageReceived: noOp);
+      };
+    }
+
+    expect(createChannel('1Alarm'), throwsAssertionError);
+    expect(createChannel('foo.bar'), throwsAssertionError);
+    expect(createChannel(''), throwsAssertionError);
+  });
+
+  testWidgets('Unique JavaScript channel names are required',
+      (WidgetTester tester) async {
+    await tester.pumpWidget(
+      WebView(
+        initialUrl: 'https://youtube.com',
+        // TODO(iskakaushik): Remove this when collection literals makes it to stable.
+        // ignore: prefer_collection_literals
+        javascriptChannels: <JavascriptChannel>[
+          JavascriptChannel(
+              name: 'Alarm', onMessageReceived: (JavascriptMessage msg) {}),
+          JavascriptChannel(
+              name: 'Alarm', onMessageReceived: (JavascriptMessage msg) {}),
+        ].toSet(),
+      ),
+    );
+    expect(tester.takeException(), isNot(null));
+  });
+
+  testWidgets('JavaScript channels update', (WidgetTester tester) async {
+    await tester.pumpWidget(
+      WebView(
+        initialUrl: 'https://youtube.com',
+        // TODO(iskakaushik): Remove this when collection literals makes it to stable.
+        // ignore: prefer_collection_literals
+        javascriptChannels: <JavascriptChannel>[
+          JavascriptChannel(
+              name: 'Tts', onMessageReceived: (JavascriptMessage msg) {}),
+          JavascriptChannel(
+              name: 'Alarm', onMessageReceived: (JavascriptMessage msg) {}),
+        ].toSet(),
+      ),
+    );
+
+    await tester.pumpWidget(
+      WebView(
+        initialUrl: 'https://youtube.com',
+        // TODO(iskakaushik): Remove this when collection literals makes it to stable.
+        // ignore: prefer_collection_literals
+        javascriptChannels: <JavascriptChannel>[
+          JavascriptChannel(
+              name: 'Tts', onMessageReceived: (JavascriptMessage msg) {}),
+          JavascriptChannel(
+              name: 'Alarm2', onMessageReceived: (JavascriptMessage msg) {}),
+          JavascriptChannel(
+              name: 'Alarm3', onMessageReceived: (JavascriptMessage msg) {}),
+        ].toSet(),
+      ),
+    );
+
+    final FakePlatformWebView platformWebView =
+        fakePlatformViewsController.lastCreatedView;
+
+    expect(platformWebView.javascriptChannelNames,
+        unorderedEquals(<String>['Tts', 'Alarm2', 'Alarm3']));
+  });
+
+  testWidgets('Remove all JavaScript channels and then add',
+      (WidgetTester tester) async {
+    // This covers a specific bug we had where after updating javascriptChannels to null,
+    // updating it again with a subset of the previously registered channels fails as the
+    // widget's cache of current channel wasn't properly updated when updating javascriptChannels to
+    // null.
+    await tester.pumpWidget(
+      WebView(
+        initialUrl: 'https://youtube.com',
+        // TODO(iskakaushik): Remove this when collection literals makes it to stable.
+        // ignore: prefer_collection_literals
+        javascriptChannels: <JavascriptChannel>[
+          JavascriptChannel(
+              name: 'Tts', onMessageReceived: (JavascriptMessage msg) {}),
+        ].toSet(),
+      ),
+    );
+
+    await tester.pumpWidget(
+      const WebView(
+        initialUrl: 'https://youtube.com',
+      ),
+    );
+
+    await tester.pumpWidget(
+      WebView(
+        initialUrl: 'https://youtube.com',
+        // TODO(iskakaushik): Remove this when collection literals makes it to stable.
+        // ignore: prefer_collection_literals
+        javascriptChannels: <JavascriptChannel>[
+          JavascriptChannel(
+              name: 'Tts', onMessageReceived: (JavascriptMessage msg) {}),
+        ].toSet(),
+      ),
+    );
+
+    final FakePlatformWebView platformWebView =
+        fakePlatformViewsController.lastCreatedView;
+
+    expect(platformWebView.javascriptChannelNames,
+        unorderedEquals(<String>['Tts']));
+  });
+
+  testWidgets('JavaScript channel messages', (WidgetTester tester) async {
+    final List<String> ttsMessagesReceived = <String>[];
+    final List<String> alarmMessagesReceived = <String>[];
+    await tester.pumpWidget(
+      WebView(
+        initialUrl: 'https://youtube.com',
+        // TODO(iskakaushik): Remove this when collection literals makes it to stable.
+        // ignore: prefer_collection_literals
+        javascriptChannels: <JavascriptChannel>[
+          JavascriptChannel(
+              name: 'Tts',
+              onMessageReceived: (JavascriptMessage msg) {
+                ttsMessagesReceived.add(msg.message);
+              }),
+          JavascriptChannel(
+              name: 'Alarm',
+              onMessageReceived: (JavascriptMessage msg) {
+                alarmMessagesReceived.add(msg.message);
+              }),
+        ].toSet(),
+      ),
+    );
+
+    final FakePlatformWebView platformWebView =
+        fakePlatformViewsController.lastCreatedView;
+
+    expect(ttsMessagesReceived, isEmpty);
+    expect(alarmMessagesReceived, isEmpty);
+
+    platformWebView.fakeJavascriptPostMessage('Tts', 'Hello');
+    platformWebView.fakeJavascriptPostMessage('Tts', 'World');
+
+    expect(ttsMessagesReceived, <String>['Hello', 'World']);
+  });
+
+  group('$PageStartedCallback', () {
+    testWidgets('onPageStarted is not null', (WidgetTester tester) async {
+      String returnedUrl;
+
+      await tester.pumpWidget(WebView(
+        initialUrl: 'https://youtube.com',
+        onPageStarted: (String url) {
+          returnedUrl = url;
+        },
+      ));
+
+      final FakePlatformWebView platformWebView =
+          fakePlatformViewsController.lastCreatedView;
+
+      platformWebView.fakeOnPageStartedCallback();
+
+      expect(platformWebView.currentUrl, returnedUrl);
+    });
+
+    testWidgets('onPageStarted is null', (WidgetTester tester) async {
+      await tester.pumpWidget(const WebView(
+        initialUrl: 'https://youtube.com',
+        onPageStarted: null,
+      ));
+
+      final FakePlatformWebView platformWebView =
+          fakePlatformViewsController.lastCreatedView;
+
+      // The platform side will always invoke a call for onPageStarted. This is
+      // to test that it does not crash on a null callback.
+      platformWebView.fakeOnPageStartedCallback();
+    });
+
+    testWidgets('onPageStarted changed', (WidgetTester tester) async {
+      String returnedUrl;
+
+      await tester.pumpWidget(WebView(
+        initialUrl: 'https://youtube.com',
+        onPageStarted: (String url) {},
+      ));
+
+      await tester.pumpWidget(WebView(
+        initialUrl: 'https://youtube.com',
+        onPageStarted: (String url) {
+          returnedUrl = url;
+        },
+      ));
+
+      final FakePlatformWebView platformWebView =
+          fakePlatformViewsController.lastCreatedView;
+
+      platformWebView.fakeOnPageStartedCallback();
+
+      expect(platformWebView.currentUrl, returnedUrl);
+    });
+  });
+
+  group('$PageFinishedCallback', () {
+    testWidgets('onPageFinished is not null', (WidgetTester tester) async {
+      String returnedUrl;
+
+      await tester.pumpWidget(WebView(
+        initialUrl: 'https://youtube.com',
+        onPageFinished: (String url) {
+          returnedUrl = url;
+        },
+      ));
+
+      final FakePlatformWebView platformWebView =
+          fakePlatformViewsController.lastCreatedView;
+
+      platformWebView.fakeOnPageFinishedCallback();
+
+      expect(platformWebView.currentUrl, returnedUrl);
+    });
+
+    testWidgets('onPageFinished is null', (WidgetTester tester) async {
+      await tester.pumpWidget(const WebView(
+        initialUrl: 'https://youtube.com',
+        onPageFinished: null,
+      ));
+
+      final FakePlatformWebView platformWebView =
+          fakePlatformViewsController.lastCreatedView;
+
+      // The platform side will always invoke a call for onPageFinished. This is
+      // to test that it does not crash on a null callback.
+      platformWebView.fakeOnPageFinishedCallback();
+    });
+
+    testWidgets('onPageFinished changed', (WidgetTester tester) async {
+      String returnedUrl;
+
+      await tester.pumpWidget(WebView(
+        initialUrl: 'https://youtube.com',
+        onPageFinished: (String url) {},
+      ));
+
+      await tester.pumpWidget(WebView(
+        initialUrl: 'https://youtube.com',
+        onPageFinished: (String url) {
+          returnedUrl = url;
+        },
+      ));
+
+      final FakePlatformWebView platformWebView =
+          fakePlatformViewsController.lastCreatedView;
+
+      platformWebView.fakeOnPageFinishedCallback();
+
+      expect(platformWebView.currentUrl, returnedUrl);
+    });
+  });
+
+  group('navigationDelegate', () {
+    testWidgets('hasNavigationDelegate', (WidgetTester tester) async {
+      await tester.pumpWidget(const WebView(
+        initialUrl: 'https://youtube.com',
+      ));
+
+      final FakePlatformWebView platformWebView =
+          fakePlatformViewsController.lastCreatedView;
+
+      expect(platformWebView.hasNavigationDelegate, false);
+
+      await tester.pumpWidget(WebView(
+        initialUrl: 'https://youtube.com',
+        navigationDelegate: (NavigationRequest r) => null,
+      ));
+
+      expect(platformWebView.hasNavigationDelegate, true);
+    });
+
+    testWidgets('Block navigation', (WidgetTester tester) async {
+      final List<NavigationRequest> navigationRequests = <NavigationRequest>[];
+
+      await tester.pumpWidget(WebView(
+          initialUrl: 'https://youtube.com',
+          navigationDelegate: (NavigationRequest request) {
+            navigationRequests.add(request);
+            // Only allow navigating to https://flutter.dev
+            return request.url == 'https://flutter.dev'
+                ? NavigationDecision.navigate
+                : NavigationDecision.prevent;
+          }));
+
+      final FakePlatformWebView platformWebView =
+          fakePlatformViewsController.lastCreatedView;
+
+      expect(platformWebView.hasNavigationDelegate, true);
+
+      platformWebView.fakeNavigate('https://www.google.com');
+      // The navigation delegate only allows navigation to https://flutter.dev
+      // so we should still be in https://youtube.com.
+      expect(platformWebView.currentUrl, 'https://youtube.com');
+      expect(navigationRequests.length, 1);
+      expect(navigationRequests[0].url, 'https://www.google.com');
+      expect(navigationRequests[0].isForMainFrame, true);
+
+      platformWebView.fakeNavigate('https://flutter.dev');
+      await tester.pump();
+      expect(platformWebView.currentUrl, 'https://flutter.dev');
+    });
+  });
+
+  group('debuggingEnabled', () {
+    testWidgets('enable debugging', (WidgetTester tester) async {
+      await tester.pumpWidget(const WebView(
+        debuggingEnabled: true,
+      ));
+
+      final FakePlatformWebView platformWebView =
+          fakePlatformViewsController.lastCreatedView;
+
+      expect(platformWebView.debuggingEnabled, true);
+    });
+
+    testWidgets('defaults to false', (WidgetTester tester) async {
+      await tester.pumpWidget(const WebView());
+
+      final FakePlatformWebView platformWebView =
+          fakePlatformViewsController.lastCreatedView;
+
+      expect(platformWebView.debuggingEnabled, false);
+    });
+
+    testWidgets('can be changed', (WidgetTester tester) async {
+      final GlobalKey key = GlobalKey();
+      await tester.pumpWidget(WebView(key: key));
+
+      final FakePlatformWebView platformWebView =
+          fakePlatformViewsController.lastCreatedView;
+
+      await tester.pumpWidget(WebView(
+        key: key,
+        debuggingEnabled: true,
+      ));
+
+      expect(platformWebView.debuggingEnabled, true);
+
+      await tester.pumpWidget(WebView(
+        key: key,
+        debuggingEnabled: false,
+      ));
+
+      expect(platformWebView.debuggingEnabled, false);
+    });
+  });
+
+  group('Custom platform implementation', () {
+    setUpAll(() {
+      WebView.platform = MyWebViewPlatform();
+    });
+    tearDownAll(() {
+      WebView.platform = null;
+    });
+
+    testWidgets('creation', (WidgetTester tester) async {
+      await tester.pumpWidget(
+        const WebView(
+          initialUrl: 'https://youtube.com',
+          gestureNavigationEnabled: true,
+        ),
+      );
+
+      final MyWebViewPlatform builder = WebView.platform;
+      final MyWebViewPlatformController platform = builder.lastPlatformBuilt;
+
+      expect(
+          platform.creationParams,
+          MatchesCreationParams(CreationParams(
+            initialUrl: 'https://youtube.com',
+            webSettings: WebSettings(
+              javascriptMode: JavascriptMode.disabled,
+              hasNavigationDelegate: false,
+              debuggingEnabled: false,
+              userAgent: WebSetting<String>.of(null),
+              gestureNavigationEnabled: true,
+            ),
+            // TODO(iskakaushik): Remove this when collection literals makes it to stable.
+            // ignore: prefer_collection_literals
+            javascriptChannelNames: Set<String>(),
+          )));
+    });
+
+    testWidgets('loadUrl', (WidgetTester tester) async {
+      WebViewController controller;
+      await tester.pumpWidget(
+        WebView(
+          initialUrl: 'https://youtube.com',
+          onWebViewCreated: (WebViewController webViewController) {
+            controller = webViewController;
+          },
+        ),
+      );
+
+      final MyWebViewPlatform builder = WebView.platform;
+      final MyWebViewPlatformController platform = builder.lastPlatformBuilt;
+
+      final Map<String, String> headers = <String, String>{
+        'header': 'value',
+      };
+
+      await controller.loadUrl('https://google.com', headers: headers);
+
+      expect(platform.lastUrlLoaded, 'https://google.com');
+      expect(platform.lastRequestHeaders, headers);
+    });
+  });
+  testWidgets('Set UserAgent', (WidgetTester tester) async {
+    await tester.pumpWidget(const WebView(
+      initialUrl: 'https://youtube.com',
+      javascriptMode: JavascriptMode.unrestricted,
+    ));
+
+    final FakePlatformWebView platformWebView =
+        fakePlatformViewsController.lastCreatedView;
+
+    expect(platformWebView.userAgent, isNull);
+
+    await tester.pumpWidget(const WebView(
+      initialUrl: 'https://youtube.com',
+      javascriptMode: JavascriptMode.unrestricted,
+      userAgent: 'UA',
+    ));
+
+    expect(platformWebView.userAgent, 'UA');
+  });
+}
+
+class FakePlatformWebView {
+  FakePlatformWebView(int id, Map<dynamic, dynamic> params) {
+    if (params.containsKey('initialUrl')) {
+      final String initialUrl = params['initialUrl'];
+      if (initialUrl != null) {
+        history.add(initialUrl);
+        currentPosition++;
+      }
+    }
+    if (params.containsKey('javascriptChannelNames')) {
+      javascriptChannelNames =
+          List<String>.from(params['javascriptChannelNames']);
+    }
+    javascriptMode = JavascriptMode.values[params['settings']['jsMode']];
+    hasNavigationDelegate =
+        params['settings']['hasNavigationDelegate'] ?? false;
+    debuggingEnabled = params['settings']['debuggingEnabled'];
+    userAgent = params['settings']['userAgent'];
+    channel = MethodChannel(
+        'plugins.flutter.io/webview_$id', const StandardMethodCodec());
+    channel.setMockMethodCallHandler(onMethodCall);
+  }
+
+  MethodChannel channel;
+
+  List<String> history = <String>[];
+  int currentPosition = -1;
+  int amountOfReloadsOnCurrentUrl = 0;
+  bool hasCache = true;
+
+  String get currentUrl => history.isEmpty ? null : history[currentPosition];
+  JavascriptMode javascriptMode;
+  List<String> javascriptChannelNames;
+
+  bool hasNavigationDelegate;
+  bool debuggingEnabled;
+  String userAgent;
+
+  Future<dynamic> onMethodCall(MethodCall call) {
+    switch (call.method) {
+      case 'loadUrl':
+        final Map<dynamic, dynamic> request = call.arguments;
+        _loadUrl(request['url']);
+        return Future<void>.sync(() {});
+      case 'updateSettings':
+        if (call.arguments['jsMode'] != null) {
+          javascriptMode = JavascriptMode.values[call.arguments['jsMode']];
+        }
+        if (call.arguments['hasNavigationDelegate'] != null) {
+          hasNavigationDelegate = call.arguments['hasNavigationDelegate'];
+        }
+        if (call.arguments['debuggingEnabled'] != null) {
+          debuggingEnabled = call.arguments['debuggingEnabled'];
+        }
+        userAgent = call.arguments['userAgent'];
+        break;
+      case 'canGoBack':
+        return Future<bool>.sync(() => currentPosition > 0);
+        break;
+      case 'canGoForward':
+        return Future<bool>.sync(() => currentPosition < history.length - 1);
+        break;
+      case 'goBack':
+        currentPosition = max(-1, currentPosition - 1);
+        return Future<void>.sync(() {});
+        break;
+      case 'goForward':
+        currentPosition = min(history.length - 1, currentPosition + 1);
+        return Future<void>.sync(() {});
+      case 'reload':
+        amountOfReloadsOnCurrentUrl++;
+        return Future<void>.sync(() {});
+        break;
+      case 'currentUrl':
+        return Future<String>.value(currentUrl);
+        break;
+      case 'evaluateJavascript':
+        return Future<dynamic>.value(call.arguments);
+        break;
+      case 'addJavascriptChannels':
+        final List<String> channelNames = List<String>.from(call.arguments);
+        javascriptChannelNames.addAll(channelNames);
+        break;
+      case 'removeJavascriptChannels':
+        final List<String> channelNames = List<String>.from(call.arguments);
+        javascriptChannelNames
+            .removeWhere((String channel) => channelNames.contains(channel));
+        break;
+      case 'clearCache':
+        hasCache = false;
+        return Future<void>.sync(() {});
+    }
+    return Future<void>.sync(() {});
+  }
+
+  void fakeJavascriptPostMessage(String jsChannel, String message) {
+    final StandardMethodCodec codec = const StandardMethodCodec();
+    final Map<String, dynamic> arguments = <String, dynamic>{
+      'channel': jsChannel,
+      'message': message
+    };
+    final ByteData data = codec
+        .encodeMethodCall(MethodCall('javascriptChannelMessage', arguments));
+    ServicesBinding.instance.defaultBinaryMessenger
+        .handlePlatformMessage(channel.name, data, (ByteData data) {});
+  }
+
+  // Fakes a main frame navigation that was initiated by the webview, e.g when
+  // the user clicks a link in the currently loaded page.
+  void fakeNavigate(String url) {
+    if (!hasNavigationDelegate) {
+      print('no navigation delegate');
+      _loadUrl(url);
+      return;
+    }
+    final StandardMethodCodec codec = const StandardMethodCodec();
+    final Map<String, dynamic> arguments = <String, dynamic>{
+      'url': url,
+      'isForMainFrame': true
+    };
+    final ByteData data =
+        codec.encodeMethodCall(MethodCall('navigationRequest', arguments));
+    ServicesBinding.instance.defaultBinaryMessenger
+        .handlePlatformMessage(channel.name, data, (ByteData data) {
+      final bool allow = codec.decodeEnvelope(data);
+      if (allow) {
+        _loadUrl(url);
+      }
+    });
+  }
+
+  void fakeOnPageStartedCallback() {
+    final StandardMethodCodec codec = const StandardMethodCodec();
+
+    final ByteData data = codec.encodeMethodCall(MethodCall(
+      'onPageStarted',
+      <dynamic, dynamic>{'url': currentUrl},
+    ));
+
+    ServicesBinding.instance.defaultBinaryMessenger.handlePlatformMessage(
+      channel.name,
+      data,
+      (ByteData data) {},
+    );
+  }
+
+  void fakeOnPageFinishedCallback() {
+    final StandardMethodCodec codec = const StandardMethodCodec();
+
+    final ByteData data = codec.encodeMethodCall(MethodCall(
+      'onPageFinished',
+      <dynamic, dynamic>{'url': currentUrl},
+    ));
+
+    ServicesBinding.instance.defaultBinaryMessenger.handlePlatformMessage(
+      channel.name,
+      data,
+      (ByteData data) {},
+    );
+  }
+
+  void _loadUrl(String url) {
+    history = history.sublist(0, currentPosition + 1);
+    history.add(url);
+    currentPosition++;
+    amountOfReloadsOnCurrentUrl = 0;
+  }
+}
+
+class _FakePlatformViewsController {
+  FakePlatformWebView lastCreatedView;
+
+  Future<dynamic> fakePlatformViewsMethodHandler(MethodCall call) {
+    switch (call.method) {
+      case 'create':
+        final Map<dynamic, dynamic> args = call.arguments;
+        final Map<dynamic, dynamic> params = _decodeParams(args['params']);
+        lastCreatedView = FakePlatformWebView(
+          args['id'],
+          params,
+        );
+        return Future<int>.sync(() => 1);
+      default:
+        return Future<void>.sync(() {});
+    }
+  }
+
+  void reset() {
+    lastCreatedView = null;
+  }
+}
+
+Map<dynamic, dynamic> _decodeParams(Uint8List paramsMessage) {
+  final ByteBuffer buffer = paramsMessage.buffer;
+  final ByteData messageBytes = buffer.asByteData(
+    paramsMessage.offsetInBytes,
+    paramsMessage.lengthInBytes,
+  );
+  return const StandardMessageCodec().decodeMessage(messageBytes);
+}
+
+class _FakeCookieManager {
+  _FakeCookieManager() {
+    final MethodChannel channel = const MethodChannel(
+      'plugins.flutter.io/cookie_manager',
+      StandardMethodCodec(),
+    );
+    channel.setMockMethodCallHandler(onMethodCall);
+  }
+
+  bool hasCookies = true;
+
+  Future<bool> onMethodCall(MethodCall call) {
+    switch (call.method) {
+      case 'clearCookies':
+        bool hadCookies = false;
+        if (hasCookies) {
+          hadCookies = true;
+          hasCookies = false;
+        }
+        return Future<bool>.sync(() {
+          return hadCookies;
+        });
+        break;
+    }
+    return Future<bool>.sync(() => null);
+  }
+
+  void reset() {
+    hasCookies = true;
+  }
+}
+
+class MyWebViewPlatform implements WebViewPlatform {
+  MyWebViewPlatformController lastPlatformBuilt;
+
+  @override
+  Widget build({
+    BuildContext context,
+    CreationParams creationParams,
+    @required WebViewPlatformCallbacksHandler webViewPlatformCallbacksHandler,
+    @required WebViewPlatformCreatedCallback onWebViewPlatformCreated,
+    Set<Factory<OneSequenceGestureRecognizer>> gestureRecognizers,
+  }) {
+    assert(onWebViewPlatformCreated != null);
+    lastPlatformBuilt = MyWebViewPlatformController(
+        creationParams, gestureRecognizers, webViewPlatformCallbacksHandler);
+    onWebViewPlatformCreated(lastPlatformBuilt);
+    return Container();
+  }
+
+  @override
+  Future<bool> clearCookies() {
+    return Future<bool>.sync(() => null);
+  }
+}
+
+class MyWebViewPlatformController extends WebViewPlatformController {
+  MyWebViewPlatformController(this.creationParams, this.gestureRecognizers,
+      WebViewPlatformCallbacksHandler platformHandler)
+      : super(platformHandler);
+
+  CreationParams creationParams;
+  Set<Factory<OneSequenceGestureRecognizer>> gestureRecognizers;
+
+  String lastUrlLoaded;
+  Map<String, String> lastRequestHeaders;
+
+  @override
+  Future<void> loadUrl(String url, Map<String, String> headers) {
+    equals(1, 1);
+    lastUrlLoaded = url;
+    lastRequestHeaders = headers;
+    return null;
+  }
+}
+
+class MatchesWebSettings extends Matcher {
+  MatchesWebSettings(this._webSettings);
+
+  final WebSettings _webSettings;
+
+  @override
+  Description describe(Description description) =>
+      description.add('$_webSettings');
+
+  @override
+  bool matches(
+      covariant WebSettings webSettings, Map<dynamic, dynamic> matchState) {
+    return _webSettings.javascriptMode == webSettings.javascriptMode &&
+        _webSettings.hasNavigationDelegate ==
+            webSettings.hasNavigationDelegate &&
+        _webSettings.debuggingEnabled == webSettings.debuggingEnabled &&
+        _webSettings.gestureNavigationEnabled ==
+            webSettings.gestureNavigationEnabled &&
+        _webSettings.userAgent == webSettings.userAgent;
+  }
+}
+
+class MatchesCreationParams extends Matcher {
+  MatchesCreationParams(this._creationParams);
+
+  final CreationParams _creationParams;
+
+  @override
+  Description describe(Description description) =>
+      description.add('$_creationParams');
+
+  @override
+  bool matches(covariant CreationParams creationParams,
+      Map<dynamic, dynamic> matchState) {
+    return _creationParams.initialUrl == creationParams.initialUrl &&
+        MatchesWebSettings(_creationParams.webSettings)
+            .matches(creationParams.webSettings, matchState) &&
+        orderedEquals(_creationParams.javascriptChannelNames)
+            .matches(creationParams.javascriptChannelNames, matchState);
+  }
+}