Skip to content

Disposal Lifecycle and KeepAlive Patterns

Every web view, headless instance, and localhost server in ZikZak InAppWebView owns native or platform resources that must be released deterministically. This page explains the single disposal contract that unifies those wrappers, the three-state disposal lifecycle that makes disposal both idempotent and keep-alive-aware, and the keep-alive mechanism that lets a native web view outlive its Dart-side controller for reuse. It closes with the headless live-instance cap and eviction interplay, and the real defect (bug #295) that motivated the current design. The material is scoped to the disposal contract and its keep-alive semantics; controller APIs and platform-native teardown details live on their own pages.

Sources: disposable.dart, spec.md

The entire disposal story rests on one deliberately minimal interface. Disposable declares a single method whose only parameter is the isKeepAlive flag, defaulting to false. There is no return type beyond void, which means disposal accessed through the interface is fire-and-forget; callers that need to await native teardown (notably the headless path) use the concrete wrapper’s Future<void> override instead. This one signature is the canonical contract every resource-owning wrapper conforms to, and the test suite pins it with a compile-time probe so any drift in the parameter name or type breaks the build rather than silently diverging.

Sources: disposable.dart, disposable_pattern_test.dart

Four public wrappers are held to this contract, verified by a compile-time assignability check that fails to compile if any wrapper drops implements Disposable:

Wrapper Owns dispose return Guarded?
InAppWebViewController Native web view + JS/Dart handler state void Yes (three-state)
InAppWebView (widget) Native platform-view widget void No (forwards)
HeadlessInAppWebView Background native web view Future<void> Yes (three-state)
InAppLocalhostServer Local HttpServer void Yes (three-state)

Sources: disposable_pattern_test.dart, in_app_webview_controller.dart, in_app_webview.dart, in_app_localhost_server.dart

A naïve disposal guard uses a single bool _disposed flag, set true on the first dispose() and checked to short-circuit every later call. That works for plain idempotency but cannot express keep-alive: because a dispose(isKeepAlive: true) also flips _disposed to true, the subsequent plain dispose() — the one that must fully release the retained native view — gets swallowed as a duplicate. The fix, introduced for bug #295, replaces the boolean with an enum, DisposeLifecycle, carrying three states: notDisposed, keepAliveHeld, and released. The guard now blocks only identical repeats, so the keepAliveHeld → released transition is allowed through while released → anything and keepAliveHeld → keepAliveHeld remain terminal no-ops.

The following diagram shows the lifecycle as a state machine. dispose(false) is the plain release; dispose(true) is the keep-alive hold. Any arrow leaving released is absent by design — release is terminal.

stateDiagram-v2
[*] --> notDisposed
notDisposed --> released: dispose(false)
notDisposed --> keepAliveHeld: dispose(true)
keepAliveHeld --> released: dispose(false)
keepAliveHeld --> keepAliveHeld: dispose(true) [no-op]
released --> released: dispose(any) [no-op]

The transition matrix below is the authoritative summary the implementation encodes; each guarded wrapper reproduces it exactly.

From \ Call dispose(false) dispose(true)
notDisposed forwards, → released forwards, → keepAliveHeld
keepAliveHeld forwards, → released no-op
released no-op no-op

Sources: dispose_lifecycle.dart, assessment.md

A subtle but critical detail governs concurrency: the lifecycle field is updated synchronously at the start of dispose, before the platform call is awaited. This keeps overlapping dispose calls serialized and lets the idempotency guard reason about state without waiting on native teardown, which is what makes the “concurrent dispose invokes the platform at most once” guarantee hold.

Sources: headless_in_app_webview.dart, headless_dispose_guard_test.dart

Although all guarded wrappers share the transition matrix, they differ in return type and in the side effects that fire on a real (non-keep-alive) release. The controller and headless view forward isKeepAlive straight to the platform; the widget forwards without a guard because its State.dispose also calls platform.dispose(); the localhost server stops its HttpServer on the first dispose regardless of the flag. The table contrasts the concrete behavior.

Wrapper On dispose(true) On dispose(false) Extra release work
InAppWebViewController forwards true, holds forwards false, releases platform clears JS/handler state
InAppWebView forwards true forwards false State.dispose also calls platform.dispose()
HeadlessInAppWebView forwards true, holds forwards false, removes from live set _liveInstances.remove(this) on clean release
InAppLocalhostServer stops server if running stops server if running unawaited(close()), swallows async close error

Sources: in_app_webview_controller.dart, in_app_webview.dart, headless_in_app_webview.dart, in_app_localhost_server.dart

The headless wrapper adds one more nuance: because its dispose returns a Future, and disposal itself never throws, the wrapper exposes lastDisposeError. After awaiting dispose(), a caller reads this to distinguish a clean native teardown from one that failed — the headless dispose only removes the instance from the live set when !isKeepAlive && lastDisposeError == null, so a failed release does not silently drop tracking. The localhost server handles the analogous async-close hazard by wrapping close() in unawaited(...catchError((_) {})), ensuring an in-flight close Future can never surface as an unhandled async error.

Sources: headless_in_app_webview.dart, headless_in_app_webview.dart, platform_headless_in_app_webview.dart, in_app_localhost_server.dart

Keep-alive is the feature that makes the three-state lifecycle necessary. An InAppWebViewKeepAlive is a lightweight token — essentially an id — passed into an InAppWebView (or its headless variant). When the widget is disposed with isKeepAlive: true, the Dart-side controller releases its references but the native web view is retained, keyed by that token, so a future widget can reattach to the same live native instance and preserve its state. The token also carries a companion InAppWebViewControllerKeepAliveProps bundle (JavaScript handler maps, user scripts, web-message listeners, injected scripts) that the platform saves and restores across the keep-alive boundary.

Sources: in_app_webview_keep_alive.dart, in_app_webview.dart

The relationship between the token, the Dart wrapper, and the retained native view is shown below. A keep-alive dispose detaches the Dart side but leaves the native instance parked under its token; a later plain dispose (or an explicit disposeKeepAlive) is what actually tears the native instance down.

flowchart LR
Token["InAppWebViewKeepAlive\n(id + saved props)"]
Wrapper["InAppWebView /\nHeadlessInAppWebView"]
Native["Native WebView\n(retained)"]
Wrapper -->|"dispose(isKeepAlive: true)"| Detach["Dart refs released"]
Detach -.->|"native retained under id"| Native
Token -.->|"keys"| Native
Wrapper -->|"dispose() plain"| Release["Native fully released"]
Release --> Native
Static["InAppWebViewController.disposeKeepAlive(token)"] -->|"explicit teardown"| Native

The platform side of keep-alive is explicit. On Android, dispose(isKeepAlive: true) keeps the method-call handler registered and skips clearing the JS/handler maps, whereas dispose(isKeepAlive: false) removes the handler and clears all controller state; a separate static disposeKeepAlive(keepAlive) invokes a native disposeKeepAlive method by token and nulls the saved props. disposeKeepAlive is officially supported on Android and iOS, and the base platform interface throws UnimplementedError elsewhere, so keep-alive retention is a platform-gated capability rather than a universal guarantee.

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

Headless web views add a process-wide ceiling on how many can run at once, and disposal is the mechanism that keeps the count honest. HeadlessInAppWebView.maxLiveWebViews defaults per platform (iOS/Android 3, macOS 5, others 8) and must be set before the first run(), otherwise the setter throws a StateError. Each run() adds the instance to a static _liveInstances set and lazily configures the native cap (retrying if the platform registered late or a transient channel error occurred); a clean plain dispose() removes it again.

Sources: headless_in_app_webview.dart, headless_in_app_webview.dart, headless_cap_test.dart

Eviction is where disposal and the cap intersect. When the native manager recycles the least-recently-used instance to stay under the cap, it fires an onEvicted callback before clearing the per-instance channel handler. The platform Dart layer routes this to _handleNativeEviction, which sets the lifecycle straight to released and removes the instance from the live set. This ensures a recycled instance stops advertising itself as live, so a later dispose() becomes the documented no-op instead of a second teardown of a dead channel — the eviction path and the disposal guard converge on the same terminal state.

Sources: platform_headless_in_app_webview.dart, headless_in_app_webview.dart

The Defect That Shaped the Design (Bug #295)

Section titled “The Defect That Shaped the Design (Bug #295)”

The three-state lifecycle was not designed in a vacuum; it is the remediation for a concrete leak. During the spec 013 TDD run, two behaviors (a keep-alive dispose followed by a plain release) could not be driven green without contradicting the already-passing idempotent-double-dispose behavior. The root cause was exactly the single-boolean guard described earlier: keepAliveHeld set _disposed = true, so the release call was rejected as a duplicate and the retained native view was never freed. Notably, the controller and widget paths forwarded isKeepAlive with no guard, which is why they were never affected — the leak lived only where the boolean guard existed (headless and localhost server).

Sources: assessment.md, issue.md

The chosen remediation was the keep-alive-aware three-state guard, preferred over introducing a new public releaseKeepAlive() API because it preserves the existing dispose() surface while fixing the leak. The trade-off recorded in the assessment is regression risk: any change to the guard had to keep double-dispose a no-op (FR-008) while enabling the release transition (FR-007), which is precisely what the transition matrix guarantees.

Sources: assessment.md, dispose_lifecycle.dart

The disposal contract is verified without any live native web view, using platform fakes that count dispose invocations and record the last isKeepAlive value. The headless guard tests enumerate the full matrix — dispose-before-run, idempotent double dispose, concurrent dispose, keep-alive hold, plain release after hold, and no-op after release — while the controller/widget tests confirm forwarding and the localhost-server tests confirm the server is closed exactly once and never double-closed. Because these are pure Dart tests against fakes, they run in the standard test runner and gate the contract on every CI run.

Sources: headless_dispose_guard_test.dart, in_app_webview_dispose_test.dart, in_app_localhost_server_dispose_test.dart

Having established how resources are released and retained, continue with the controller and widget surface that these wrappers expose in InAppWebView Widget and InAppWebViewController, the background instance whose cap and eviction you saw here in Headless WebView and the Live-Instance Cap, and the session-reuse patterns that build on keep-alive in VCR Cassettes and the WebView Pool. For the native teardown that each platform performs behind platform.dispose, see Android Native Layer (Java) and Apple Native Layer (Swift and Swift Package Manager).