Skip to content

InAppWebView Widget and InAppWebViewController

InAppWebView is the inline, platform-view-backed WebView widget; InAppWebViewController is the imperative handle you receive once the native view exists. Together they form the single most-used surface of the package, and they are deliberately thin: the widget is a parameter marshalling shell that hands a creation-params object to a federated platform implementation, and the controller is a dual-layer facade that groups a very large API into four domain facades while forwarding everything else straight to the platform controller. Understanding that division — what is decided in Dart before the platform view is born, what is decided by the native side at creation time, and what is pure passthrough — is what lets you reason about callback timing, settings inference, and disposal without reading native code.

Sources: in_app_webview.dart, platform_inappwebview_widget.dart

Architectural Position: Two Objects, Three Layers

Section titled “Architectural Position: Two Objects, Three Layers”

The widget and the controller are not peers. The widget owns a PlatformInAppWebViewWidget, which is the object that actually returns a Flutter Widget from build(context); the controller is constructed by the platform side during platform-view creation and handed back to you through a callback. This inversion is the reason onWebViewCreated exists at all: before the platform view is created there is no native WebView to command, so there is no valid controller to hold.

flowchart TD
A["InAppWebView (StatefulWidget)\ncreation params + callbacks"] --> B["PlatformInAppWebViewWidget\nbuild(context) → platform view"]
B --> C["Native platform view\nAndroid View / WKWebView / NSView / iframe"]
C -->|"onPlatformViewCreated(id)"| D["PlatformInAppWebViewController\n(id, webviewParams)"]
D -->|"controllerFromPlatform()"| E["InAppWebViewController\nhanded to onWebViewCreated"]
E --> F["navigation / javaScript / cookies / settings"]
E --> G["everything else → platform passthrough"]

The widget class itself is almost entirely a factory: InAppWebView.fromPlatformCreationParams wraps your arguments into PlatformInAppWebViewWidgetCreationParams and delegates to InAppWebView.fromPlatform, whose only job is to hold the platform field and forward build/dispose. The owning _InAppWebViewState simply calls widget.platform.build(context) and, on teardown, widget.platform.dispose().

Sources: in_app_webview.dart, in_app_webview.dart

Constructing the Widget: What You Pass and Where It Goes

Section titled “Constructing the Widget: What You Pass and Where It Goes”

The factory accepts four initial load alternatives, a settings object, an optional script list, and roughly fifty event callbacks. Three of the four load sources are mutually exclusive in practice — pick one of initialUrlRequest, initialFile, or initialData; the platform receives all of them as separate creation-param keys and the native side decides precedence.

Constructor argument Wire key Purpose Notes
initialUrlRequest initialUrlRequest Load a URL with headers/method POST bodies work, but Android ignores headers for POST
initialFile initialFile Load an app asset file See loadFile semantics
initialData initialData Load an in-memory HTML string Carries mimeType, encoding, baseUrl, historyUrl
initialSettings initialSettings Engine configuration Serialized to JSON, then inferred per platform
initialUserScripts initialUserScripts Scripts injected at document start/end Ignored on iOS when windowId is set
keepAlive keepAliveId Retain the native view across widget rebuilds Must be released via disposeKeepAlive
headlessWebView headlessWebViewId Adopt an existing headless native view Its id overrides the platform view id
windowId windowId Attach to a window opened by onCreateWindow Constrains several capabilities on iOS
pullToRefreshController pullToRefreshSettings Swipe-to-refresh Android requires useHybridComposition
contextMenu contextMenu Custom context-menu items Android + iOS only
webViewEnvironment — Shared native environment Windows only
gestureRecognizers — Win gesture arena conflicts E.g. nesting in a ListView

Sources: in_app_webview.dart, in_app_webview.dart, platform_webview.dart

Two behaviors are worth internalizing because they surprise intermediate developers. First, the factory injects a controllerFromPlatform closure of its own, so the object handed to onWebViewCreated is always the app-facing InAppWebViewController, never the raw platform controller. Second, the factory wraps your onWebViewCreated to attach the Network Capture manager before your callback runs, which is why a JS handler registered by the capture layer is already present inside your callback.

Sources: in_app_webview.dart, network_capture_manager.dart

The Creation Sequence and the Controller Handoff

Section titled “The Creation Sequence and the Controller Handoff”

The handoff is where most timing bugs live. Each platform package builds its platform view, waits for the native onPlatformViewCreated callback, resolves a view id, constructs the platform controller, and only then invokes onWebViewCreated.

sequenceDiagram
participant App
participant Widget as InAppWebView
participant PV as PlatformInAppWebViewWidget
participant Native
App->>Widget: InAppWebView(initialUrlRequest: ...)
Widget->>PV: PlatformInAppWebViewWidgetCreationParams
PV->>Native: build(context) + creationParams
Native-->>PV: onPlatformViewCreated(id)
PV->>PV: resolve viewId
PV->>Native: PlatformInAppWebViewController(id, webviewParams)
Native-->>PV: controllerFromPlatform(platformController)
PV-->>App: onWebViewCreated(InAppWebViewController)
App->>Native: loadUrl / evaluateJavascript / handlers

The view-id resolution order is identical on Android and iOS and is the single most useful detail for debugging “my controller talks to the wrong WebView”: a running headlessWebView id wins first, then keepAlive.id, then the platform view id. The resolved id is also passed to pullToRefreshController.init(viewId) and findInteractionController.init(viewId), so those helpers bind to the same native view your controller commands.

Sources: in_app_webview.dart, in_app_webview.dart

macOS is the outlier: it derives the controller directly from the platform view id and calls its own controllerFromPlatform helper rather than the params.controllerFromPlatform closure, while the Web implementation routes through params.controllerFromPlatform and reuses it for onLoadStart/onLoadStop dispatch. Android and iOS cache the app-facing controller in _controllerFromPlatform and use it for every subsequent event dispatch, which guarantees the object identity in onLoadStart is the same object you stored in onWebViewCreated.

Sources: in_app_webview.dart, in_app_webview_web_element.dart, in_app_webview_controller.dart

Controller Anatomy: Four Facades Plus a Passthrough

Section titled “Controller Anatomy: Four Facades Plus a Passthrough”

InAppWebViewController implements Disposable and holds exactly one field of substance — platform — plus four lazily created facades. The facade split (issue #161, P3) is a grouping refactor with no behavior change: each facade method delegates to _controller.platform, and the monolith routes the same call back through the facade, so both entry points reach the identical native invocation.

Accessor Facade Owns Backed by
controller.navigation NavigationController loadUrl, loadData, loadFile, postUrl, reload, history navigation, clearHistory platform
controller.javaScript JavaScriptController evaluateJavascript, callAsyncJavaScript, injection, JS handlers, user scripts platform
controller.cookies CookieController Cookie CRUD scoped to the current URL shared CookieManager.instance()
controller.settings SettingsController getSettings / setSettings platform

The facades are created once and memoized (_navigationController ??= NavigationController(this)), so accessor identity is stable across calls. CookieController is the only facade with real logic: it resolves an omitted url to await _controller.platform.getUrl() and returns an empty list / null / false when no URL is available yet, which is the correct behavior during early lifecycle phases.

Sources: in_app_webview_controller.dart, navigation_controller.dart, cookie_controller.dart, settings_controller.dart

Everything outside those four domains is a one-line forward to platform, with three recurring patterns: wrapping (printCurrentPage and createWebMessageChannel rewrap the returned platform object in its app-facing type), static (a family of static members goes through PlatformInAppWebViewController.static(), a separate factory used only to reach process-wide operations such as clearAllCache, setWebContentsDebuggingEnabled, and getDefaultUserAgent), and local (getViewId, pressKey, injectCSS*, takeScreenshot, scroll and zoom helpers).

Sources: in_app_webview_controller.dart, in_app_webview_controller.dart, in_app_webview_controller.dart, platform_inappwebview_controller.dart

Two convenience members sit outside the facade model and are worth knowing: networkCaptureController resolves the capture collector through an Expando registry keyed on both the app controller and its platform, and webStorage rewraps platform.webStorage on each access.

Sources: in_app_webview_controller.dart, network_capture_manager.dart

Settings Inference: Callbacks Silently Enable Engine Features

Section titled “Settings Inference: Callbacks Silently Enable Engine Features”

Several callbacks only fire if a corresponding use* setting is enabled. Rather than making you set both, Android and iOS infer the setting from the presence of the callback, but only when you left the setting null. This is why passing initialSettings matters: an explicit true/false always wins over inference.

Callback present Inferred setting
shouldOverrideUrlLoading useShouldOverrideUrlLoading
onLoadResource useOnLoadResource
onDownloadStartRequest useOnDownloadStart
shouldInterceptAjaxRequest / onAjaxProgress / onAjaxReadyStateChange useShouldInterceptAjaxRequest
shouldInterceptFetchRequest useShouldInterceptFetchRequest
shouldInterceptRequest useShouldInterceptRequest
onRenderProcessGone useOnRenderProcessGone
onNavigationResponse useOnNavigationResponse
any onNetwork* callback or settings.networkCapture useNetworkCapture

The inference runs inside build(context), not in the constructor, and its output is what gets serialized into the initialSettings creation-params key. The Network Capture case is handled one layer earlier, in the widget factory, via NetworkCaptureManager.maybeCreate, which returns null when capture is off and otherwise also merges an interceptor UserScript into initialUserScripts.

Sources: in_app_webview.dart, in_app_webview.dart, in_app_webview.dart, network_capture_manager.dart

Android additionally defaults useHybridComposition to true when unset, which selects initExpensiveAndroidView over initSurfaceAndroidView and is a hard prerequisite for pull-to-refresh.

Sources: in_app_webview.dart, in_app_webview.dart

Disposal: A Three-State Lifecycle, Not a Boolean

Section titled “Disposal: A Three-State Lifecycle, Not a Boolean”

Both InAppWebView and InAppWebViewController accept dispose({bool isKeepAlive = false}). A naive boolean “already disposed” flag breaks the keepAlive flow, because a keepAlive dispose must leave the native view alive and still allow a later plain dispose() to fully release it. The package therefore models disposal as DisposeLifecycle with three states, and only identical repeats are no-ops.

From state dispose() (release) dispose(isKeepAlive: true)
notDisposed forwards, → released forwards, → keepAliveHeld
keepAliveHeld forwards, → released no-op
released no-op no-op

The widget layer adds its own idempotent _disposed guard and combines the explicit argument with the creation param (isKeepAlive || params.keepAlive != null), so a widget constructed with a keepAlive never accidentally releases the retained native view. On the native side, a keepAlive dispose keeps the method-call handler registered and preserves handler maps, user scripts, injected scripts, and web message channels; a full dispose clears all of them.

Sources: dispose_lifecycle.dart, in_app_webview_controller.dart, in_app_webview.dart, in_app_webview_controller.dart

The behavioral contract is pinned by unit tests that count platform dispose invocations, including the non-obvious cases: a repeated keepAlive dispose while held must not re-reach the platform, and a keepAlive dispose after full release must not either.

Sources: in_app_webview_dispose_test.dart

Render-Ready Waits: waitForSelector and waitForDomSettled

Section titled “Render-Ready Waits: waitForSelector and waitForDomSettled”

onLoadStop fires on the native didFinish, before the page’s own scripts populate the DOM. To avoid every consumer hand-rolling a polling loop, the package ships an extension on InAppWebViewController that provides two bounded, cancellable waits implemented purely over evaluateJavascript, so they work on every engine without per-platform native code.

Method Condition Key parameters Result extras
waitForSelector(selector) document.querySelector(selector) is truthy timeout 10 s, pollInterval 100 ms probeCount
waitForDomSettled() DOM fingerprint unchanged for N probes stableSamples 3 (must be ≥ 1) stableSamples, fingerprint

Both return a WebViewRenderWait whose result future completes exactly once with WebViewRenderStatus.satisfied, timedOut, cancelled, or failed. Cancellation is cooperative: a probe already in flight when you call cancel() has its result discarded rather than reported, and every completion path funnels through a single isCompleted guard to prevent Bad state: Future already completed.

Sources: webview_render_wait.dart, webview_render_wait.dart, webview_render_wait.dart

The widget is available on every supported engine, but the creation params are not uniformly honored, and unimplemented controller methods throw UnimplementedError from the platform interface rather than silently no-op.

Capability Android iOS macOS Web Windows
InAppWebView widget PlatformViewLink UiKitView AppKitView custom element yes
keepAlive yes yes partial no no
headlessWebView adoption yes yes no yes no
contextMenu yes yes no no no
pullToRefreshController yes yes no no no
webViewEnvironment no no no no yes
preventGestureDelay no yes no no no

Sources: platform_inappwebview_widget.dart, platform_inappwebview_controller.dart, in_app_webview.dart

The canonical usage pattern is to store the controller from onWebViewCreated and issue every command through it, as the example app does — the callback assignment is the synchronization point, and calling loadUrl from within it is safe and common.

InAppWebViewController? controller;
InAppWebView(
initialSettings: InAppWebViewSettings(javaScriptEnabled: true),
initialUrlRequest: URLRequest(url: WebUri('https://flutter.dev')),
onWebViewCreated: (c) => controller = c,
onLoadStop: (c, url) async {
final html = await c.getHtml();
},
)

Sources: in_app_webiew_example.screen.dart, in_app_webiew_example.screen.dart

Symptom Likely cause Where to look
Callback never fires Required use* setting explicitly set to false Inference table above
Controller acts on the wrong page headlessWebView or keepAlive id overrides the platform view id _onPlatformViewCreated
Native view leaks after navigation dispose(isKeepAlive: true) without a later plain dispose() DisposeLifecycle
Double-dispose crash Custom wrapper bypassing the lifecycle guard dispose guard
Scraped DOM is empty despite onLoadStop Page scripts not finished; use a render wait waitForDomSettled
Pull-to-refresh inert on Android useHybridComposition not enabled build inference

The controller’s facades are the entry point to the domain-specific pages: Cookies, Web Storage, and Credential Management and Content Blockers, Proxy, and Tracing. For the no-widget variant of the same controller, read Headless WebView and the Live-Instance Cap; for teardown semantics in depth, Disposal Lifecycle and KeepAlive Patterns. To understand why the widget can be this thin, the contract seam is documented in The Platform Interface: The Contract Seam, and the facade rationale in Domain Controller Facades: Navigation, JavaScript, Cookies, Settings. JavaScript callback registration is covered end to end in The JavaScript Bridge Global and Handler Wiring.