Some content already lives on the web: a payment page, a help center, a team dashboard. Rebuilding it as native screens costs weeks, and every update then needs an app release. A WebView renders the real page inside your Flutter app, with your own app bar, navigation rules, and JavaScript bridge around it. This guide builds a complete WebView feature with webview_flutter: setup, JavaScript communication, navigation control, back-button handling, progress and error states, and cookies.
A WebView is one of three ways to show web content from a Flutter app. Deep links are covered in Flutter Deep Linking: App Links Guide, and native navigation stays with Flutter go_router: The Navigation Guide. This article covers the embedded browser case.
What is webview_flutter in Flutter?
webview_flutter is the official Flutter plugin that embeds a native browser view in a Flutter app, using Android WebView on Android and WKWebView on iOS. A developer creates a WebViewController, configures JavaScript mode and a navigation delegate, loads a URL or HTML string, and places a WebViewWidget in the tree. The page renders with the platform engine, so modern HTML, CSS, and JavaScript work without extra setup. webview_flutter is the right choice for payment pages, help centers, terms screens, and any content a team already maintains on the web. Because the Flutter team maintains the plugin, its API stays aligned with current Flutter releases, and a page that renders correctly in a mobile browser renders the same way inside the app.
Use webview_flutter when the content must stay inside the app under app control, such as intercepting a redirect after payment. Use a browser tab instead when the user is simply leaving to read a public page. The comparison table later in this article lays out the trade-offs, and the official package documentation lives at pub.dev/packages/webview_flutter.
How do you add a WebView to a Flutter app?
Add a WebView by installing webview_flutter, granting the Android internet permission, creating a WebViewController in initState, and returning a WebViewWidget from build. The controller is the API surface: it loads pages, runs JavaScript, and reports navigation events through a NavigationDelegate. Creating it once in initState, rather than in build, keeps the page alive across rebuilds. The example below loads a help center page and enables JavaScript, which most real pages require. The same controller pattern works for every WebView screen: a checkout screen and an embedded dashboard differ only in URL, navigation rules, and JavaScript channels. One controller per screen keeps page state isolated, so closing a screen disposes its page cleanly.
dependencies:
webview_flutter: ^4.10.0
On Android, the app needs the internet permission in AndroidManifest.xml, because a release build without it renders a blank page:
<uses-permission android:name="android.permission.INTERNET"/>
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
class HelpCenterScreen extends StatefulWidget {
const HelpCenterScreen({super.key});
@override
State<HelpCenterScreen> createState() => _HelpCenterScreenState();
}
class _HelpCenterScreenState extends State<HelpCenterScreen> {
late final WebViewController _controller;
@override
void initState() {
super.initState();
_controller = WebViewController()
..setJavaScriptMode(JavaScriptMode.unrestricted)
..loadRequest(Uri.parse('https://example.com/help'));
}
@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(title: const Text('Help Center')),
body: WebViewWidget(controller: _controller),
);
}
JavaScriptMode.unrestricted lets the page run its scripts, which payment forms need; disable JavaScript only for static documents. On iOS, App Transport Security blocks plain HTTP, so load HTTPS URLs.
How do you load local HTML and run JavaScript?
Load local HTML with loadHtmlString on WebViewController, and run JavaScript in the page with runJavaScript or runJavaScriptReturningResult. loadHtmlString renders HTML without a network request, suiting generated receipts, legal text, and offline help content. A baseUrl argument makes relative links and images inside the HTML resolve against a real origin. JavaScript runs in the page context, so a Dart call can read the page title, fill a form field, or scroll to an element. Timing matters: run JavaScript after the page finishes loading, signaled by onPageFinished, because a script run against a half-loaded document fails silently. Scripts that must run on every load belong in that callback.
await controller.loadHtmlString(html, baseUrl: 'https://example.com');
await controller.runJavaScript('window.scrollTo(0, 0)');
final title = await controller.runJavaScriptReturningResult('document.title');
Communication also runs from the page into Dart through a JavaScript channel registered with addJavaScriptChannel. A checkout page posts an order id when payment completes, and Dart reacts by closing the WebView:
_controller.addJavaScriptChannel(
'PaymentResult',
onMessageReceived: (JavaScriptMessage message) {
debugPrint('Payment finished for order ${message.message}');
},
);
The page posts with PaymentResult.postMessage('order-1234'). Treat every channel message as untrusted input and validate the payload in Dart before acting on it, exactly as a server validates a request body. The same discipline applies to API responses, as described in Flutter REST API Integration: From JSON to UI.
How do you control navigation inside a WebView?
Control navigation with a NavigationDelegate, whose onNavigationRequest callback inspects every URL the page tries to open and returns NavigationDecision.navigate to allow it or NavigationDecision.prevent to block it. Navigation control turns a WebView from a hole in the app into a feature: a payment flow watches for the success redirect, blocks it, and shows a native confirmation instead. The same callback keeps external links, such as a social profile, from taking over the embedded view. Redirect chains pass through the callback one hop at a time, so a provider redirecting through intermediate domains still ends at a success URL the callback can catch. Allowlist by domain rather than exact URL, because providers add query parameters that exact matching would miss.
_controller.setNavigationDelegate(
NavigationDelegate(
onNavigationRequest: (NavigationRequest request) {
final url = request.url;
if (url.startsWith('https://example.com/checkout/success')) {
Navigator.of(context).pop('paid');
return NavigationDecision.prevent;
}
return url.startsWith('https://example.com')
? NavigationDecision.navigate
: NavigationDecision.prevent;
},
),
);
The Android back button needs matching care: without handling, back exits the screen even when the WebView has its own history. Wrap the screen in a PopScope that asks canGoBack first, going back inside the page when history exists and popping the route only at the first page.
return PopScope(
canPop: false,
onPopInvokedWithResult: (bool didPop, Object? result) async {
if (didPop) return;
if (await _controller.canGoBack()) {
await _controller.goBack();
} else if (context.mounted) {
Navigator.of(context).pop();
}
},
child: Scaffold(
appBar: AppBar(title: const Text('Help Center')),
body: WebViewWidget(controller: _controller),
),
);
How do you show loading progress and handle errors?
Show loading progress through the onProgress callback of the NavigationDelegate, which reports progress from 0 to 100, and handle failures through onWebResourceError, which reports the error code when a resource fails to load. A thin LinearProgressIndicator under the app bar shows the page is working, and an error state with a retry button turns a dead network into a recoverable moment instead of a blank screen. Both callbacks live on the same NavigationDelegate used for navigation control. Progress values arrive unevenly, jumping from 10 to 70 as the main document lands, so the indicator should animate between values instead of snapping. Hide it entirely at 100, because a finished bar reads as a stuck page.
int _progress = 0;
String? _errorMessage;
_controller.setNavigationDelegate(
NavigationDelegate(
onProgress: (int progress) => setState(() => _progress = progress),
onWebResourceError: (WebResourceError error) {
if (error.isForMainFrame ?? false) {
setState(() => _errorMessage =
'This page could not be loaded. Check your connection.');
}
},
),
);
if (_progress < 100) LinearProgressIndicator(value: _progress / 100),
When _errorMessage is set, swap the WebViewWidget for a message with a FilledButton that clears the error and calls reload, so one tap retries the page.
The isForMainFrame check matters: a failed analytics script also triggers onWebResourceError, so reserve the full-screen error for main-frame failures. The Flutter documentation on platform integration explains how plugins bridge Dart and the native view.
How do you manage cookies and clear the cache?
Manage cookies with WebViewCookieManager, which sets cookies the WebView sends with requests and clears them on demand, and clear cached files with clearCache and clearLocalStorage on WebViewController. Cookie control matters when the app holds a session token: set the session cookie before loading, and the page opens already signed in. Clearing cookies and cache at sign-out keeps one account session from leaking into the next account on a shared device. Cached pages deserve the same treatment, because a cached account page can render personal data from disk before any request runs. Sign-out cleanup clears all three stores: cookies, cache, and local storage.
await WebViewCookieManager().setCookie(
WebViewCookie(name: 'session', value: token, domain: 'example.com', path: '/'),
);
// At sign-out:
await WebViewCookieManager().clearCookies();
await controller.clearCache();
await controller.clearLocalStorage();
Set the cookie before the first loadRequest, because the page reads cookies when the request goes out. Match the cookie domain to the page domain exactly, since a mismatched domain is silently ignored and the page opens signed out.
WebView, browser tab, or system browser: which should you use?
Choose a WebView when the app must control the page, a browser tab when the user only reads a page with a visible URL, and the system browser when content belongs fully outside the app. The options differ in control, trust signals, and maintenance. A WebView gives full control over navigation and JavaScript but hides the URL bar, so users cannot verify the domain on a payment page. A browser tab shows the real URL and shares the browser session, which builds trust but removes app control. The system browser removes the app from the flow entirely, suiting links that were never part of the app experience. Maintenance differs too: a WebView page needs testing against two engines, while a browser tab inherits browser updates for free.
| Option | App control | URL visible | Shared browser session | Best for |
|---|---|---|---|---|
| WebView (webview_flutter) | Full: navigation, JavaScript, cookies | No | No | Payments, help centers, dashboards |
| Browser tab (Custom Tab / Safari VC) | Minimal | Yes | Yes | Articles, OAuth sign-in |
| System browser (url_launcher) | None | Yes | Yes | External links that leave the app |
OAuth deserves a warning: Google and other providers block sign-in inside embedded WebViews, so OAuth belongs in a browser tab. Payments are the opposite case, where watching for the success redirect inside a WebView is standard. Decide per feature, because one app often needs all three options.
What are the common WebView mistakes to avoid?
The common WebView mistakes are creating the controller in build, forgetting the Android internet permission, loading plain HTTP URLs, trusting channel messages without validation, and skipping back-button handling. Each produces a confusing symptom: a page reloading on rebuild, a blank screen in release builds only, a page failing on iOS, or a back press exiting mid-checkout. The table below maps each mistake to its fix. Most share one root cause: the WebView is treated as a static widget instead of a living browser with its own history, storage, and lifecycle. Treating the controller as the owner of that lifecycle, created once and configured before the first load, prevents most failures in the table.
| Mistake | Symptom | Fix |
|---|---|---|
| Controller created in build | Page reloads on rebuild | Create the controller in initState |
| Missing INTERNET permission | Blank page in release builds | Add it to AndroidManifest.xml |
| Plain HTTP URL | Page blocked on iOS | Load HTTPS URLs only |
| Unvalidated channel messages | Page scripts trigger app actions | Validate payloads in Dart |
| No back handling | Back exits mid-flow | PopScope with canGoBack |
| Cookie set after load | Page opens signed out | Set cookies before loadRequest |
Conclusion
A WebView earns its place when web content must live inside the app under app control: webview_flutter embeds the platform browser, a NavigationDelegate guards navigation, JavaScript channels connect the page to Dart, and cookie management keeps sessions correct. Handle progress, errors, and the back button, and the embedded page feels native instead of a shortcut. Keep OAuth flows out of WebViews entirely.
Building a Flutter app with embedded web content or payments? Get in touch and let's talk about your project.
Originally published at uzairxdev.online
Top comments (0)