Flutter development practice-use of webview plug-in flutter_inappwebview

Flutter development practice-use of webview plug-in flutter_inappwebview

During the development process, we often encounter the need to use WebView, and Webview needs to call native plug-ins to implement it. Common flutter webview plug-ins are webview_flutter and flutter_inappwebview. I sorted out webview_flutter before, check https://blog.csdn.net/gloryFlow/article/details/131683122

Here we use flutter_inappwebview to load web pages.

1. Introduction of flutter_inappwebview

To use flutter_inappwebview, you need to introduce the plug-in in pubspec.yaml.

 # Browser
  flutter_inappwebview: 5.4.3 + 7

2. Use flutter_inappwebview

Before using the flutter_inappwebview plug-in, let’s first look at the properties of the webview provided by flutter_inappwebview

WebView(
      {<!-- -->this.windowId,
      this.onWebViewCreated,
      this.onLoadStart,
      this.onLoadStop,
      this.onLoadError,
      this.onLoadHttpError,
      this.onProgressChanged,
      this.onConsoleMessage,
      this.shouldOverrideUrlLoading,
      this.onLoadResource,
      this.onScrollChanged,
      @Deprecated('Use `onDownloadStartRequest` instead')
          this.onDownloadStart,
      this.onDownloadStartRequest,
      this.onLoadResourceCustomScheme,
      this.onCreateWindow,
      this.onCloseWindow,
      this.onJsAlert,
      this.onJsConfirm,
      this.onJsPrompt,
      this.onReceivedHttpAuthRequest,
      this.onReceivedServerTrustAuthRequest,
      this.onReceivedClientCertRequest,
      this.onFindResultReceived,
      this.shouldInterceptAjaxRequest,
      this.onAjaxReadyStateChange,
      this.onAjaxProgress,
      this.shouldInterceptFetchRequest,
      this.onUpdateVisitedHistory,
      this.onPrint,
      this.onLongPressHitTestResult,
      this.onEnterFullscreen,
      this.onExitFullscreen,
      this.onPageCommitVisible,
      this.onTitleChanged,
      this.onWindowFocus,
      this.onWindowBlur,
      this.onOverScrolled,
      this.onZoomScaleChanged,
      this.androidOnSafeBrowsingHit,
      this.androidOnPermissionRequest,
      this.androidOnGeolocationPermissionsShowPrompt,
      this.androidOnGeolocationPermissionsHidePrompt,
      this.androidShouldInterceptRequest,
      this.androidOnRenderProcessGone,
      this.androidOnRenderProcessResponsive,
      this.androidOnRenderProcessUnresponsive,
      this.androidOnFormResubmission,
      @Deprecated('Use `onZoomScaleChanged` instead')
          this.androidOnScaleChanged,
      this.androidOnReceivedIcon,
      this.androidOnReceivedTouchIconUrl,
      this.androidOnJsBeforeUnload,
      this.androidOnReceivedLoginRequest,
      this.iosOnWebContentProcessDidTerminate,
      this.iosOnDidReceiveServerRedirectForProvisionalNavigation,
      this.iosOnNavigationResponse,
      this.iosShouldAllowDeprecatedTLS,
      this.initialUrlRequest,
      this.initialFile,
      this.initialData,
      this.initialOptions,
      this.contextMenu,
      this.initialUserScripts,
      this.pullToRefreshController,
      this.implementation = WebViewImplementation.NATIVE});
}

List some commonly used ones

  • initialUrlRequest: request to load url
  • initialUserScripts: script for initialization settings
  • initialOptions: Configuration of initialization settings
  • onWebViewCreated: callback after webview is created
  • onTitleChanged: Monitoring callback for webpage title change
  • onLoadStart: The web page starts loading
  • shouldOverrideUrlLoading: Determine whether the route can be replaced, for example, you can control certain connections to not allow jumps.
  • onLoadStop: Web page loading ends
  • onProgressChanged: page loading progress progress
  • onLoadError: Page loading failed
  • onUpdateVisitedHistory; update the visited history page callback
  • onConsoleMessage: console message, used to output console.log information

Load web pages using WebView

class WebViewInAppScreen extends StatefulWidget {<!-- -->
  const WebViewInAppScreen({<!-- -->
    Key? key,
    required this.url,
    this.onWebProgress,
    this.onWebResourceError,
    required this.onLoadFinished,
    required this.onWebTitleLoaded,
    this.onWebViewCreated,
  }): super(key: key);

  final String url;
  final Function(int progress)? onWebProgress;
  final Function(String? errorMessage)? onWebResourceError;
  final Function(String? url) onLoadFinished;
  final Function(String? webTitle)? onWebTitleLoaded;
  final Function(InAppWebViewController controller)? onWebViewCreated;

  @override
  State<WebViewInAppScreen> createState() => _WebViewInAppScreenState();
}

class _WebViewInAppScreenState extends State<WebViewInAppScreen> {<!-- -->
  final GlobalKey webViewKey = GlobalKey();

  InAppWebViewController? webViewController;
  InAppWebViewOptions viewOptions = InAppWebViewOptions(
    useShouldOverrideUrlLoading: true,
    mediaPlaybackRequiresUserGesture: true,
    applicationNameForUserAgent: "dface-yjxdh-webview",
  );

  @override
  void initState() {<!-- -->
    // TODO: implement initState
    super.initState();
  }

  @override
  void dispose() {<!-- -->
    // TODO: implement dispose
    webViewController?.clearCache();
    super.dispose();
  }

  //Set page title
  void setWebPageTitle(data) {<!-- -->
    if (widget.onWebTitleLoaded != null) {<!-- -->
      widget.onWebTitleLoaded!(data);
    }
  }

  // flutter calls H5 method
  void callJSMethod() {<!-- -->
    
  }

  @override
  Widget build(BuildContext context) {<!-- -->
    return Column(
      children: <Widget>[
        Expanded(
          child: InAppWebView(
            key: webViewKey,
            initialUrlRequest: URLRequest(url: Uri.parse(widget.url)),
            initialUserScripts: UnmodifiableListView<UserScript>([
              UserScript(
                  source:
                      "document.cookie='token=${<!-- -->ApiAuth().token};domain='.laileshuo.cb';path=/'",
                  injectionTime: UserScriptInjectionTime.AT_DOCUMENT_START),
            ]),
            initialOptions: InAppWebViewGroupOptions(
              crossPlatform: viewOptions,
            ),
            onWebViewCreated: (controller) {<!-- -->
              webViewController = controller;

              if (widget.onWebViewCreated != null) {<!-- -->
                widget.onWebViewCreated!(controller);
              }
            },
            onTitleChanged: (controller, title) {<!-- -->
              if (widget.onWebTitleLoaded != null) {<!-- -->
                widget.onWebTitleLoaded!(title);
              }
            },
            onLoadStart: (controller, url) {<!-- -->},
            shouldOverrideUrlLoading: (controller, navigationAction) async {<!-- -->
              //Allow route replacement
              return NavigationActionPolicy.ALLOW;
            },
            onLoadStop: (controller, url) async {<!-- -->

              // Loading completed
              widget.onLoadFinished(url.toString());
            },
            onProgressChanged: (controller, progress) {<!-- -->
              if (widget.onWebProgress != null) {<!-- -->
                widget.onWebProgress!(progress);
              }
            },
            onLoadError: (controller, Uri? url, int code, String message) {<!-- -->
              if (widget.onWebResourceError != null) {<!-- -->
                widget.onWebResourceError!(message);
              }
            },
            onUpdateVisitedHistory: (controller, url, androidIsReload) {<!-- -->},
            onConsoleMessage: (controller, consoleMessage) {<!-- -->
              print(consoleMessage);
            },
          ),
        ),
        Container(
          height: ScreenUtil().bottomBarHeight + 50.0,
          color: Colors.white,
          child: Column(
            children: [
              Expanded(
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: <Widget>[
                    ElevatedButton(
                      child: Icon(Icons.arrow_back),
                      onPressed: () {<!-- -->
                        webViewController?.goBack();
                      },
                    ),
                    SizedBox(
                      width: 25.0,
                    ),
                    ElevatedButton(
                      child: Icon(Icons.arrow_forward),
                      onPressed: () {<!-- -->
                        webViewController?.goForward();
                      },
                    ),
                    SizedBox(
                      width: 25.0,
                    ),
                    ElevatedButton(
                      child: Icon(Icons.refresh),
                      onPressed: () {<!-- -->
                        // callJSMethod();
                        webViewController?.reload();
                      },
                    ),
                  ],
                ),
              ),
              Container(
                height: ScreenUtil().bottomBarHeight,
              ),
            ],
          ),
        ),
      ],
    );
  }
}

3. Summary

Flutter development practice-use of webview plug-in flutter_inappwebview. The description may not be accurate, please forgive me.

https://blog.csdn.net/gloryFlow/article/details/133489866

Study and record, keep improving every day.