Adding WebView to your Flutter app

1. Introduction

With the webview_flutter plugin, you can embed a WebViewWidget directly into your Android or iOS Flutter app. On iOS, the widget is backed by a WKWebView, while on Android it is backed by a WebView. Because the web view participates in Flutter's widget tree, you can layer standard Flutter widgets—such as progress bars, toolbars, and menus—directly over the web content.

What you'll build

In this codelab, you'll collaborate with Google Antigravity to iteratively build a mobile Flutter application featuring an embedded web view. Your finished app will:

  • Display live web content inside a WebViewWidget.
  • Layer Flutter widgets (such as a LinearProgressIndicator and PopupMenuButton) over the web view.
  • React to page load progress events (onPageStarted, onProgress, and onPageFinished).
  • Control navigation history (back, forward, and reload) through a shared WebViewController.
  • Intercept and block specific domains using a NavigationDelegate.
  • Evaluate JavaScript expressions and read returned results from the page context.
  • Receive asynchronous messages from JavaScript in Dart using JavaScript channels.
  • Inspect, add, set, remove, and clear browser cookies with WebViewCookieManager.
  • Load and render HTML from bundled Flutter assets, local device files, and raw HTML strings.

iPhone simulator running a Flutter app with an embedded webview showing the Flutter.dev homepage

Android emulator running a Flutter app with an embedded webview showing the Flutter.dev homepage

Your learning journey

This codelab guides you through building the WebView app step by step:

  1. Set up your Flutter environment - Configure the Flutter SDK, Google Antigravity, and an Android or iOS target device.
  2. Create a project and add a WebView - Prompt Antigravity to scaffold the project with webview_flutter and material_ui and render https://flutter.dev.
  3. Listen for page load events - Wrap the WebViewWidget in a Stack and overlay a LinearProgressIndicator driven by NavigationDelegate callbacks.
  4. Add navigation controls with WebViewController - Hoist the controller and build back, forward, and reload toolbar actions.
  5. Block navigation with NavigationDelegate and add an AppBar menu - Intercept navigation requests to specific domains and add a test menu.
  6. Evaluate JavaScript - Enable unrestricted JavaScript execution and read navigator.userAgent from the page.
  7. Communicate with JavaScript channels - Register a named SnackBar channel so page scripts can post messages back to Dart.
  8. Manage cookies - List, add, set, remove, and clear cookies using WebViewCookieManager and document.cookie.
  9. Load Flutter assets, local files, and HTML strings - Bundle local HTML and CSS assets and load pages from assets, the file system, and strings.

What you'll learn

  • How to collaborate with Google Antigravity to iteratively build and customize a WebView-powered Flutter app.
  • How to configure WebViewController and embed WebViewWidget on Android and iOS.
  • How to monitor page load progress and intercept navigation requests with NavigationDelegate.
  • How to navigate backward, forward, and reload pages programmatically.
  • How to evaluate JavaScript expressions with runJavaScript and runJavaScriptReturningResult.
  • How to establish two-way communication between JavaScript and Dart using addJavaScriptChannel.
  • How to manage cookies with WebViewCookieManager.
  • How to load local HTML content using loadFlutterAsset, loadFile, and loadHtmlString.

Prerequisites

  • Basic familiarity with Flutter widgets and Dart syntax.
  • An Android or iOS development setup (an Android Emulator, iOS Simulator, or connected physical mobile device).

2. Set up your Flutter environment

Editor

This codelab uses Google Antigravity as your AI-first development environment. In each step, you prompt Antigravity to generate or evolve your app's components, review the key webview_flutter concepts in the generated code, and optionally explore creative variations.

Choose a development target

Because webview_flutter targets mobile platforms in this codelab, run the app on one of the following devices:

  • A physical Android or iOS device connected to your computer and set to Developer mode.
  • The iOS Simulator (requires installing Xcode on macOS).
  • The Android Emulator (requires setup in Android Studio).

Install Flutter

The most up-to-date instructions on installing the Flutter SDK are always on docs.flutter.dev.

For this codelab, install the following software:

  1. Flutter SDK
  2. Google Antigravity with the official Dart and Flutter plugin enabled (available in the Plugin Marketplace under the Build with Google section).
  3. Compiler software for your chosen mobile target (Android Studio to target Android, or Xcode to target iOS).

3. Create a project and add a WebView

In this step, you prompt Antigravity to scaffold a new mobile Flutter project, add the webview_flutter plugin, and display a full-bleed WebViewWidget showing flutter.dev.

WebViews are hosted platform views. On Android, webview_flutter uses Texture Layer Hybrid Composition by default and lets you switch to Hybrid Composition, whereas iOS always uses Hybrid Composition. For a deeper comparison, see Hosting native Android and iOS views in your Flutter app with Platform Views.

Prompt Antigravity to create the project and embed a WebView

  1. Launch Google Antigravity and open an empty directory where you'd like to build your project (choose a path that doesn't require elevated privileges or contain spaces, such as a folder in your home directory or C:\src\).
  2. In the Antigravity agent chat panel, send the following prompt to create the Flutter project, add webview_flutter and material_ui, and wire up WebViewApp:
Create a new Flutter project named `webview_in_flutter` targeting Android and iOS (`--platforms=android,ios`). Add the `webview_flutter` and `material_ui` packages, and replace `lib/main.dart` (importing `package:material_ui/material_ui.dart` and `package:webview_flutter/webview_flutter.dart`) with a Material 3 `WebViewApp` stateful widget that initializes a `WebViewController` in `initState()` loading `https://flutter.dev` using `loadRequest`, and displays a `WebViewWidget` inside a `Scaffold` with an `AppBar` titled `'Flutter WebView'`. Also remove `test/widget_test.dart`.

Understanding the generated code

Initializing WebViewController and WebViewWidget

In lib/main.dart, _WebViewAppState creates a WebViewController inside initState(), instructs it to load https://flutter.dev, and passes the controller to WebViewWidget:

class _WebViewAppState extends State<WebViewApp> {
  late final WebViewController controller;

  @override
  void initState() {
    super.initState();
    controller = WebViewController()
      ..loadRequest(
        Uri.parse('https://flutter.dev'),
      );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Flutter WebView'),
      ),
      body: WebViewWidget(
        controller: controller,
      ),
    );
  }
}

Run and test the app

Run the Flutter app on your Android emulator, iOS simulator, or connected mobile device:

flutter run

The app displays https://flutter.dev in a full-screen WebViewWidget beneath the AppBar. As you scroll, you might notice that parts of the page look slightly off—that's because JavaScript is disabled by default in WebViewController. You'll enable JavaScript in a later step.

iPhone simulator running a Flutter app with an embedded webview showing the Flutter.dev homepage

Android emulator running a Flutter app with an embedded webview showing the Flutter.dev homepage

4. Listen for page load events

During a page load cycle, WebViewController fires three progress callbacks through its NavigationDelegate: onPageStarted, onProgress, and onPageFinished. In this step, you extract the web view into a dedicated WebViewStack widget that wraps WebViewWidget in a Flutter Stack and overlays a LinearProgressIndicator while a page is loading.

Prompt Antigravity to add a loading progress indicator

Send the following prompt in Antigravity:

Create `lib/src/web_view_stack.dart` (importing `package:material_ui/material_ui.dart` and `package:webview_flutter/webview_flutter.dart`) with a `WebViewStack` stateful widget that manages the `WebViewController` and a `loadingPercentage` integer state. In `initState()`, configure the controller with a `NavigationDelegate` (`onPageStarted` sets `loadingPercentage = 0`, `onProgress` updates `loadingPercentage = progress`, and `onPageFinished` sets `loadingPercentage = 100`) and load `https://flutter.dev`. In `build()`, return a `Stack` containing the `WebViewWidget` and a `LinearProgressIndicator(value: loadingPercentage / 100.0)` when `loadingPercentage < 100`. Update `lib/main.dart` so `WebViewApp` renders `const WebViewStack()` as the `Scaffold` body.

Understanding the generated code

Tracking progress with NavigationDelegate

In lib/src/web_view_stack.dart, setNavigationDelegate registers callbacks for each phase of the page load lifecycle and updates loadingPercentage with setState():

controller = WebViewController()
  ..setNavigationDelegate(
    NavigationDelegate(
      onPageStarted: (url) {
        setState(() {
          loadingPercentage = 0;
        });
      },
      onProgress: (progress) {
        setState(() {
          loadingPercentage = progress;
        });
      },
      onPageFinished: (url) {
        setState(() {
          loadingPercentage = 100;
        });
      },
    ),
  )
  ..loadRequest(Uri.parse('https://flutter.dev'));

Layering Flutter widgets over the WebViewWidget

Because WebViewWidget is a standard Flutter widget, placing it inside a Stack lets you conditionally render a LinearProgressIndicator along the top edge whenever loadingPercentage < 100:

@override
Widget build(BuildContext context) {
  return Stack(
    children: [
      WebViewWidget(
        controller: controller,
      ),
      if (loadingPercentage < 100)
        LinearProgressIndicator(
          value: loadingPercentage / 100.0,
        ),
    ],
  );
}

Run and test the app

Perform a hot restart (since initState() wiring changed) and tap a link on the page. While the new page loads, you'll see the LinearProgressIndicator fill across the top of the WebViewWidget.

5. Add navigation controls with WebViewController

Having an embedded browser is much more useful when users can navigate backward and forward through their browsing history or reload the current page. To share the WebViewController between WebViewStack and a new NavigationControls toolbar widget in the AppBar, you'll hoist the controller up into WebViewApp.

Prompt Antigravity to hoist the controller and add navigation buttons

Send the following prompt in Antigravity:

Hoist the `WebViewController` creation back into `_WebViewAppState` in `lib/main.dart`, and update `WebViewStack` in `lib/src/web_view_stack.dart` to accept `required this.controller` (keeping `setNavigationDelegate(...)` followed by `..loadRequest(Uri.parse('https://flutter.dev'))` at the end of `_WebViewStackState.initState()`). Then create `lib/src/navigation_controls.dart` (importing `package:material_ui/material_ui.dart` and `package:webview_flutter/webview_flutter.dart`) with a `NavigationControls` stateless widget that takes `required this.controller` and renders a `Row` of three `IconButton`s: back (`Icons.arrow_back_ios`, capturing `ScaffoldMessenger.of(context)` before `await`, calling `controller.goBack()` if `await controller.canGoBack()`, or showing a `'No back history item'` `SnackBar`), forward (`Icons.arrow_forward_ios`, calling `controller.goForward()` if `await controller.canGoForward()`, or showing a `'No forward history item'` `SnackBar`), and reload (`Icons.replay`, calling `controller.reload()`). Add `NavigationControls(controller: controller)` to the `AppBar.actions` list in `lib/main.dart`.

Understanding the generated code

Programmatic history navigation in NavigationControls

In lib/src/navigation_controls.dart, each IconButton queries or commands the shared WebViewController. Because canGoBack() and canGoForward() are asynchronous, capturing ScaffoldMessenger.of(context) before await safely avoids using BuildContext across an async gap:

IconButton(
  icon: const Icon(Icons.arrow_back_ios),
  onPressed: () async {
    final messenger = ScaffoldMessenger.of(context);
    if (await controller.canGoBack()) {
      await controller.goBack();
    } else {
      messenger.showSnackBar(
        const SnackBar(content: Text('No back history item')),
      );
      return;
    }
  },
),

Sharing WebViewController from WebViewApp

In lib/main.dart, _WebViewAppState owns the single WebViewController instance and passes it to both NavigationControls in the AppBar and WebViewStack in the Scaffold body:

return Scaffold(
  appBar: AppBar(
    title: const Text('Flutter WebView'),
    actions: [
      NavigationControls(controller: controller),
    ],
  ),
  body: WebViewStack(controller: controller),
);

Run and test the app

Perform a hot restart. Tap a few links inside the web view, then test the back, forward, and reload buttons in the AppBar. If you tap the back button when at the start of the history stack, a SnackBar notifies you that there is no back history item.

iPhone simulator running a Flutter app with an embedded webview showing the Flutter.dev homepage with previous page, next page, and page reload controls

Android emulator running a Flutter app with an embedded webview showing the Flutter.dev homepage with previous page, next page, and page reload controls

6. Block navigation with NavigationDelegate and add an AppBar menu

Beyond tracking load progress, NavigationDelegate lets you decide whether the WebViewWidget is allowed to navigate to a requested URL. Whenever a navigation occurs—such as when a user taps a link or your code calls loadRequest—the onNavigationRequest callback is invoked.

In this step, you configure onNavigationRequest to block navigation to youtube.com and create an AppBar menu (lib/src/menu.dart) with a Navigate to YouTube test action.

Prompt Antigravity to filter navigation and add a menu

Send the following prompt in Antigravity:

Update the `NavigationDelegate` in `lib/src/web_view_stack.dart` with an `onNavigationRequest` callback that parses `Uri.parse(navigation.url).host`: if the host contains `'youtube.com'`, show a `SnackBar` with `'Blocking navigation to $host'` and return `NavigationDecision.prevent`; otherwise return `NavigationDecision.navigate`. To test this behavior, create `lib/src/menu.dart` (importing `package:material_ui/material_ui.dart` and `package:webview_flutter/webview_flutter.dart`) with a private `_MenuOptions` enum (`navigationDelegate`) and a `Menu` widget accepting `required this.controller` that renders a `PopupMenuButton<_MenuOptions>` with a `'Navigate to YouTube'` menu item calling `controller.loadRequest(Uri.parse('https://youtube.com'))`. Add `Menu(controller: controller)` to `AppBar.actions` in `lib/main.dart`.

Understanding the generated code

Intercepting URLs with onNavigationRequest

In lib/src/web_view_stack.dart, onNavigationRequest inspects the target host and returns either NavigationDecision.prevent or NavigationDecision.navigate:

onNavigationRequest: (navigation) {
  final host = Uri.parse(navigation.url).host;
  if (host.contains('youtube.com')) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(
          'Blocking navigation to $host',
        ),
      ),
    );
    return NavigationDecision.prevent;
  }
  return NavigationDecision.navigate;
},

Adding the extensible Menu widget

In lib/src/menu.dart, PopupMenuButton<_MenuOptions> triggers controller.loadRequest when the user selects Navigate to YouTube:

return PopupMenuButton<_MenuOptions>(
  onSelected: (value) async {
    switch (value) {
      case _MenuOptions.navigationDelegate:
        await controller.loadRequest(Uri.parse('https://youtube.com'));
    }
  },
  itemBuilder: (context) => [
    const PopupMenuItem<_MenuOptions>(
      value: _MenuOptions.navigationDelegate,
      child: Text('Navigate to YouTube'),
    ),
  ],
);

Run and test the app

Perform a hot restart so the updated NavigationDelegate is registered in initState(). Open the overflow menu in the AppBar and select Navigate to YouTube. The navigation is blocked and a SnackBar displays Blocking navigation to ...youtube.com.

Android emulator running a Flutter app with an embedded webview showing the Flutter.dev homepage with a menu item showing the option to 'Navigate to YouTube'

Android emulator running a Flutter app with an embedded webview showing the Flutter.dev homepage with toast pop up reading 'Blocking navigation to m.youtube.com'

7. Evaluate JavaScript

WebViewController provides two methods for evaluating JavaScript in the context of the current page:

By default, JavaScript execution is disabled (JavaScriptMode.disabled). To evaluate scripts, you first configure the controller with setJavaScriptMode(JavaScriptMode.unrestricted).

Prompt Antigravity to enable JavaScript and inspect the user agent

Send the following prompt in Antigravity:

In `lib/src/web_view_stack.dart`, chain `..setJavaScriptMode(JavaScriptMode.unrestricted)` onto `widget.controller` in `initState()` (before `loadRequest`). Then update `lib/src/menu.dart` by converting `Menu` into a `StatefulWidget`, adding `userAgent` to `_MenuOptions`, and adding a `'Show user-agent'` `PopupMenuItem` that awaits `widget.controller.runJavaScriptReturningResult('navigator.userAgent')` and displays the returned `$userAgent` in a `SnackBar` (checking `if (!context.mounted) return;` first).

Understanding the generated code

Enabling unrestricted JavaScript mode

In lib/src/web_view_stack.dart, _WebViewStackState.initState chains setJavaScriptMode onto widget.controller:

widget.controller
  ..setNavigationDelegate(
    NavigationDelegate(
      // ...
    ),
  )
  ..setJavaScriptMode(JavaScriptMode.unrestricted)
  ..loadRequest(Uri.parse('https://flutter.dev'));

Reading a result from JavaScript in Menu

In lib/src/menu.dart, selecting _MenuOptions.userAgent evaluates 'navigator.userAgent' inside the web view and shows the returned string in a SnackBar:

case _MenuOptions.userAgent:
  final userAgent = await widget.controller
      .runJavaScriptReturningResult('navigator.userAgent');
  if (!context.mounted) return;
  ScaffoldMessenger.of(context).showSnackBar(
    SnackBar(
      content: Text('$userAgent'),
    ),
  );

Run and test the app

Perform a hot restart. Notice that flutter.dev now renders with full interactive styling because JavaScript is enabled. Open the AppBar menu and tap Show user-agent to see the browser's navigator.userAgent string in a SnackBar.

iPhone simulator running a Flutter app with an embedded webview showing the Flutter.dev homepage with menu items showing the options to 'Navigate to YouTube' or 'Show user-agent'

iPhone simulator running a Flutter app with an embedded webview showing the Flutter.dev homepage with toast pop up showing the user agent string.

8. Communicate with JavaScript channels

While runJavaScriptReturningResult is great for synchronous expressions, JavaScript code often performs asynchronous work (such as network requests, timers, or DOM events) and needs to push data back to Dart when ready.

JavaScript channels solve this by exposing a named property on the JavaScript window object. Calling <ChannelName>.postMessage(String) from JavaScript invokes the onMessageReceived callback registered in Dart using addJavaScriptChannel.

Prompt Antigravity to register a SnackBar JavaScript channel

Send the following prompt in Antigravity:

In `lib/src/web_view_stack.dart`, register a JavaScript channel on `widget.controller` in `initState()` (before `loadRequest`) using `..addJavaScriptChannel('SnackBar', onMessageReceived: (message) { ... })` that shows `message.message` in a `SnackBar`. Then update `lib/src/menu.dart` to add `javascriptChannel` to `_MenuOptions` and a `'Lookup IP Address'` `PopupMenuItem` that calls `widget.controller.runJavaScript(...)` to send a `GET` `XMLHttpRequest` to `https://api.ipify.org/?format=json`, parse `response.ip`, and post `"IP Address: " + response.ip` (or `"Error: " + req.status` on failure) to `SnackBar.postMessage(...)`.

Understanding the generated code

Registering the channel in WebViewStack

In lib/src/web_view_stack.dart, addJavaScriptChannel registers a channel named 'SnackBar' and listens for incoming messages:

..setJavaScriptMode(JavaScriptMode.unrestricted)
..addJavaScriptChannel(
  'SnackBar',
  onMessageReceived: (message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text(message.message)),
    );
  },
)
..loadRequest(Uri.parse('https://flutter.dev'));

Posting messages from JavaScript to Dart

In lib/src/menu.dart, selecting Lookup IP Address runs an asynchronous XMLHttpRequest inside the web view. When the response arrives, SnackBar.postMessage(...) sends the formatted IP string back to your Dart callback:

case _MenuOptions.javascriptChannel:
  await widget.controller.runJavaScript('''
var req = new XMLHttpRequest();
req.open('GET', "https://api.ipify.org/?format=json");
req.onload = function() {
  if (req.status == 200) {
    let response = JSON.parse(req.responseText);
    SnackBar.postMessage("IP Address: " + response.ip);
  } else {
    SnackBar.postMessage("Error: " + req.status);
  }
}
req.send();''');

Run and test the app

Perform a hot restart so the SnackBar channel is registered on the controller, then select Lookup IP Address from the menu. Once the request completes, a SnackBar displays your device's public IP address.

9. Manage cookies

Your Flutter app can inspect and modify cookies in the web view using both WebViewCookieManager and JavaScript's document.cookie API. In this step, you add five cookie management actions to Menu: listing cookies, clearing all cookies, adding a cookie using JavaScript, setting a cookie using WebViewCookieManager, and removing a cookie by expiring it.

Send the following prompt in Antigravity:

Update `lib/src/menu.dart` to manage WebView cookies using a `final cookieManager = WebViewCookieManager();` field on `_MenuState`. Add `listCookies`, `clearCookies`, `addCookie`, `setCookie`, and `removeCookie` values to `_MenuOptions` along with corresponding `PopupMenuItem` entries (`'Clear cookies'`, `'List cookies'`, `'Add cookie'`, `'Set cookie'`, and `'Remove cookie'`) and helper methods (checking `if (!mounted) return;` before showing a `SnackBar`): `_onListCookies` (runs `'document.cookie'` using `runJavaScriptReturningResult` and shows the result or `'There are no cookies.'`), `_onClearCookies` (calls `cookieManager.clearCookies()` and shows `'There were cookies. Now, they are gone!'` or `'There were no cookies to clear.'`), `_onAddCookie` (sets a `FirstName=John` cookie with a 30-day expiration using `runJavaScript` and shows `'Custom cookie added.'`), `_onSetCookie` (calls `cookieManager.setCookie` with `WebViewCookie(name: 'foo', value: 'bar', domain: 'flutter.dev')` and shows `'Custom cookie is set.'`), and `_onRemoveCookie` (expires `FirstName=John` in `1970` using `runJavaScript` and shows `'Custom cookie removed.'`).

Understanding the generated code

Clearing and setting cookies with WebViewCookieManager

In lib/src/menu.dart, WebViewCookieManager provides native cookie-jar operations such as clearCookies() (which returns a Future<bool> indicating whether any cookies were removed) and setCookie():

Future<void> _onClearCookies() async {
  final hadCookies = await cookieManager.clearCookies();
  String message = 'There were cookies. Now, they are gone!';
  if (!hadCookies) {
    message = 'There were no cookies to clear.';
  }
  if (!mounted) return;
  ScaffoldMessenger.of(context).showSnackBar(
    SnackBar(content: Text(message)),
  );
}

Future<void> _onSetCookie(WebViewController controller) async {
  await cookieManager.setCookie(
    const WebViewCookie(name: 'foo', value: 'bar', domain: 'flutter.dev'),
  );
  if (!mounted) return;
  ScaffoldMessenger.of(context).showSnackBar(
    const SnackBar(content: Text('Custom cookie is set.')),
  );
}

Reading, adding, and expiring cookies using document.cookie

You can also read or manipulate cookies directly in the page's JavaScript context:

Future<void> _onListCookies(WebViewController controller) async {
  final String cookies = await controller
      .runJavaScriptReturningResult('document.cookie') as String;
  if (!mounted) return;
  ScaffoldMessenger.of(context).showSnackBar(
    SnackBar(
      content: Text(cookies.isNotEmpty ? cookies : 'There are no cookies.'),
    ),
  );
}

Run and test the app

Hot reload the app and exercise the cookie menu items in order:

  1. Select List cookies to view the analytics cookies set by flutter.dev.
  2. Select Clear cookies to remove them (There were cookies. Now, they are gone!).
  3. Select Clear cookies a second time to verify it reports There were no cookies to clear..
  4. Select Add cookie and Set cookie, then select List cookies to see both FirstName=John and foo=bar.
  5. Select Remove cookie, then List cookies again to confirm FirstName=John was removed.

Android emulator running a Flutter app with an embedded webview showing the Flutter.dev homepage with a list of menu options covering navigating to YouTube, showing user agent, and interacting with the browser's cookie jar

Android emulator running a Flutter app with an embedded webview showing the Flutter.dev homepage with a toast dialog showing the cookies set in the browser

Android emulator running a Flutter app with an embedded webview showing the Flutter.dev homepage with a toast dialog that reads 'There were cookies. Now they are gone!'

Android emulator running a Flutter app with an embedded webview showing the Flutter.dev homepage with a toast dialog that reads 'Custom cookie added.'

10. Load Flutter assets, local files, and HTML strings

In addition to remote https:// URLs, WebViewController can render local HTML content from three sources:

  • Flutter assets bundled in pubspec.yaml using loadFlutterAsset.
  • Local files on the device's file system (resolved with path_provider) using loadFile.
  • In-memory HTML strings using loadHtmlString.

Prompt Antigravity to load local HTML assets, files, and strings

Send the following prompt in Antigravity:

Add the `path_provider` package to the project. Create `assets/www/index.html` (a demo HTML page linking to `styles/style.css`) and `assets/www/styles/style.css` (`h1 { color: blue; }`), and register both files under `flutter: assets:` in `pubspec.yaml`. Then update `lib/src/menu.dart` to define a `kExamplePage` HTML string constant, add `loadFlutterAsset`, `loadLocalFile`, and `loadHtmlString` to `_MenuOptions` with menu items (`'Load Flutter Asset'`, `'Load HTML string'`, and `'Load local file'`), and implement `_onLoadFlutterAssetExample` (`controller.loadFlutterAsset('assets/www/index.html')`), `_onLoadLocalFileExample` (writes `kExamplePage` to `'$tmpDir/www/index.html'` using `getTemporaryDirectory()` from `path_provider` and calls `controller.loadFile(...)`), and `_onLoadHtmlStringExample` (`controller.loadHtmlString(kExamplePage)`).

Understanding the generated code

Loading a bundled Flutter asset

When loading assets/www/index.html with loadFlutterAsset, relative references inside the HTML (such as <link rel="stylesheet" href="styles/style.css" />) resolve automatically against the bundled assets/www/ directory:

Future<void> _onLoadFlutterAssetExample(
  WebViewController controller,
  BuildContext context,
) async {
  await controller.loadFlutterAsset('assets/www/index.html');
}

Loading a local file and an HTML string

To demonstrate loadFile, _prepareLocalFile() writes kExamplePage into the device's temporary directory provided by getTemporaryDirectory(), and _onLoadLocalFileExample loads the resulting path. For in-memory HTML, _onLoadHtmlStringExample passes kExamplePage directly to loadHtmlString:

Future<void> _onLoadLocalFileExample(
  WebViewController controller,
  BuildContext context,
) async {
  final String pathToIndex = await _prepareLocalFile();

  await controller.loadFile(pathToIndex);
}

static Future<String> _prepareLocalFile() async {
  final String tmpDir = (await getTemporaryDirectory()).path;
  final File indexFile = File('$tmpDir/www/index.html');

  await Directory('$tmpDir/www').create(recursive: true);
  await indexFile.writeAsString(kExamplePage);

  return indexFile.path;
}

Future<void> _onLoadHtmlStringExample(
  WebViewController controller,
  BuildContext context,
) async {
  await controller.loadHtmlString(kExamplePage);
}

Run and test the app

Open the AppBar menu and test Load Flutter Asset, Load HTML string, and Load local file. Notice that Load Flutter Asset renders the <h1> heading in blue because assets/www/index.html links to assets/www/styles/style.css, whereas kExamplePage renders with default black text.

Android emulator running a Flutter app with an embedded webview showing a page labelled 'Local demo page' with the title in blue

Android emulator running a Flutter app with an embedded webview showing a page labelled 'Local demo page' with the title in black

11. Congratulations!

Congratulations! You've collaborated with Google Antigravity to build a full-featured Flutter app with an embedded WebViewWidget.

What you've built

  • Embedded a WebViewWidget controlled by a WebViewController and layered a Flutter LinearProgressIndicator on top using a Stack.
  • Built history navigation controls (canGoBack, goBack, canGoForward, goForward, and reload) and domain filtering with NavigationDelegate.
  • Executed JavaScript from Dart (runJavaScript and runJavaScriptReturningResult) and received asynchronous messages from JavaScript using addJavaScriptChannel.
  • Managed browser cookies with WebViewCookieManager and loaded local HTML from Flutter assets, device files, and strings.

Learn more