flutter_webview_plugin

repository·master·Indexed 23 days ago

https://github.com/fluttercommunity/flutter_webview_plugin

A Flutter plugin that enables communication with a native WebView. It allows developers to launch web content as a fullscreen scaffold via WebviewScaffold or within a custom rectangle using the launch() method. The plugin provides hooks for JavaScript injection via evalJavascript(), event listening through streams (such as onUrlChanged and onStateChanged), and bidirectional communication using JavascriptChannel.

Tokens
3.9K
Snippets
6
Records
21
Agent score
79%

What's inside flutter_webview_plugin

  1. Enable access to local files

    master

    To allow the WebView to load local files from the file system, set withLocalUrl: true in the launch function or WebviewScaffold.

    iOS Specifics: You must also set the localUrlScope option to a directory path. This allows all files within that directory (and subdirectories) to be accessible. If omitted on iOS, only the specific file being opened will have access, which may prevent subresources from loading. This option is ignored on Android.

  2. Configure iOS for WebView usage

    master

    To allow the plugin to load content correctly on iOS, you must add the NSAppTransportSecurity key to your ios/Runner/Info.plist file. This enables arbitrary loads for both general web content and web content specifically.

    <key>NSAppTransportSecurity</key>
    <dict>
        <key>NSAllowsArbitraryLoads</key>
        <true/>
        <key>NSAllowsArbitraryLoadsInWebContent</key>
        <true/>
    </dict>
  3. Inject JavaScript into the WebView

    master

    Use evalJavascript(String code) to execute JavaScript within the webview. This should only be called after the page has finished loading. You can monitor the onStateChanged stream and check if the state is WebViewState.finishLoad before calling the function. For large scripts, it is recommended to load them from an asset file.

    Future<String> loadJS(String name) async {
      var givenJS = rootBundle.loadString('assets/$name.js');
      return givenJS.then((String js) {
        flutterWebViewPlugin.onStateChanged.listen((viewState) async {
          if (viewState.type == WebViewState.finishLoad) {
            flutterWebViewPlugin.evalJavascript(js);
          }
        });
      });
    }
  4. Ignore SSL Errors

    master

    To display content from servers with untrusted or self-signed certificates, set ignoreSSLErrors: true in the launch function.

    Warning: Do not use this in production.

    iOS Requirement: You must also ensure NSAppTransportSecurity is configured in ios/Runner/Info.plist as described in the iOS setup guide to allow untrusted certificates to be displayed.

  5. Launch a fullscreen WebView with WebviewScaffold

    master

    Use WebviewScaffold within your Flutter widget tree to launch a fullscreen WebView. You can use the hidden parameter to show a CircularProgressIndicator while loading, or provide an initialChild widget to display a custom loading UI (e.g., a red screen with text) until the page finishes loading.

    return new MaterialApp(
      title: 'Flutter WebView Demo',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      routes: {
        '/': (_) => const MyHomePage(title: 'Flutter WebView Demo'),
        '/widget': (_) => new WebviewScaffold(
          url: selectedUrl,
          appBar: new AppBar(
            title: const Text('Widget webview'),
          ),
          withZoom: true,
          withLocalStorage: true,
          hidden: true,
          initialChild: Container(
            color: Colors.redAccent,
            child: const Center(
              child: Text('Waiting.....'),
            ),
          ),
        ),
      },
    );
  6. Listen to WebView events with FlutterWebviewPlugin

    master

    The FlutterWebviewPlugin provides a singleton instance that allows you to listen to various webview lifecycle and interaction events via streams.

    final flutterWebviewPlugin = new FlutterWebviewPlugin();
    
    // Listen for URL changes
    flutterWebviewPlugin.onUrlChanged.listen((String url) {
      // Handle URL change
    });
    
    // Listen for vertical scroll changes
    flutterWebviewPlugin.onScrollYChanged.listen((double offsetY) {
      // compare vertical scroll changes here with old value
    });
    
    // Listen for horizontal scroll changes
    flutterWebviewPlugin.onScrollXChanged.listen((double offsetX) {
      // compare horizontal scroll changes here with old value
    });
  7. Reference: FlutterWebviewPlugin methods

    master

    The following methods are available on the FlutterWebviewPlugin instance:

    • Future<String> evalJavascript(String code)
    • Future<Map<String, dynamic>> getCookies()
    • Future<Null> cleanCookies()
    • Future<Null> resize(Rect rect)
    • Future<Null> show()
    • Future<Null> hide()
    • Future<Null> reloadUrl(String url)
    • Future<Null> close()
    • Future<Null> reload()
    • Future<Null> goBack()
    • Future<Null> goForward()
    • Future<Null> stopLoading()
    • Future<bool> canGoBack()
    • Future<bool> canGoForward()
    • Future<Null> dispose()
  8. Reference: FlutterWebviewPlugin launch() parameters

    master

    The launch method accepts the following parameters:

    Future<Null> launch(String url, {
        Map<String, String> headers: null,
        Set<JavascriptChannel> javascriptChannels: null,
        bool withJavascript: true,
        bool clearCache: false,
        bool clearCookies: false,
        bool hidden: false,
        bool enableAppScheme: true,
        Rect rect: null,
        String userAgent: null,
        bool withZoom: false,
        bool displayZoomControls: false,
        bool withLocalStorage: true,
        bool withLocalUrl: true,
        String localUrlScope: null,
        bool withOverviewMode: false,
        bool scrollBar: true,
        bool supportMultipleWindows: false,
        bool appCacheEnabled: false,
        bool allowFileURLs: false,
        bool useWideViewPort: false,
        String invalidUrlRegex: null,
        bool geolocationEnabled: false,
        bool debuggingEnabled: false,
        bool ignoreSSLErrors: false,
    });
  9. Define a JavascriptChannel for communication

    master

    Use the JavascriptChannel class to create a named bridge between your Flutter application and the JavaScript running inside a web view. When you register a JavascriptChannel with a WebView, the plugin adds a property to the JavaScript window object with the specified name.

    Constraints:

    • The name must follow the regex ^[a-zA-Z_][a-zA-Z0-9]*$. It must start with a letter or underscore and can only contain alphanumeric characters and underscores.
    • Any existing JavaScript window property with the same name will be overridden.

    When JavaScript code calls window.<name>.postMessage(<message>), the onMessageReceived callback is triggered in Flutter, providing a JavascriptMessage object.

  10. Use WebviewScaffold to display a WebView

    master

    The WebviewScaffold widget provides a complete Flutter Scaffold around the WebView, handling common UI elements like an appBar, bottomNavigationBar, and persistentFooterButtons. It automatically manages the lifecycle of the underlying WebView, including launching the URL, handling resizing, and managing back navigation.

    Key configuration options include:

    • url: The initial URL to load (required).
    • appBar: A PreferredSizeWidget to display at the top.
    • javascriptChannels: A set of JavascriptChannel objects for communication between JS and Flutter.
    • ignoreSSLErrors: Set to true to bypass SSL certificate errors.
    • withZoom / displayZoomControls: Controls for pinch-to-zoom functionality.
    • clearCache / clearCookies: Boolean flags to wipe data on initialization.
    • initialChild: A widget (e.g., a CircularProgressIndicator) to show while the WebView is loading.