• flutter开发实战-webview插件flutter_inappwebview使用


    flutter开发实战-webview插件flutter_inappwebview使用

    在开发过程中,经常遇到需要使用WebView,Webview需要调用原生的插件来实现。常见的flutter的webview插件是webview_flutter,flutter_inappwebview。之前整理了一下webview_flutter,查看https://blog.csdn.net/gloryFlow/article/details/131683122

    这里我们使用flutter_inappwebview来加载网页。

    在这里插入图片描述

    一、引入flutter_inappwebview

    使用flutter_inappwebview,需要在pubspec.yaml引入插件。

      # 浏览器
      flutter_inappwebview: 5.4.3+7
    
    • 1
    • 2

    二、使用flutter_inappwebview

    使用flutter_inappwebview插件前,我们先看下flutter_inappwebview提供的webview的属性

    WebView(
          {this.windowId,
          this.onWebViewCreated,
          this.onLoadStart,
          this.onLoadStop,
          this.onLoadError,
          this.onLoadHttpError,
          this.onProgressChanged,
          this.onConsoleMessage,
          this.shouldOverrideUrlLoading,
          this.onLoadResource,
          this.onScrollChanged,
          ('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,
          ('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});
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68

    列一下常用的几个

    • initialUrlRequest:加载url的请求
    • initialUserScripts:初始化设置的script
    • initialOptions:初始化设置的配置
    • onWebViewCreated:webview创建后的callback回调
    • onTitleChanged:网页title变换的监听回调
    • onLoadStart:网页开始加载
    • shouldOverrideUrlLoading:确定路由是否可以替换,比如可以控制某些连接不允许跳转。
    • onLoadStop:网页加载结束
    • onProgressChanged:页面加载进度progress
    • onLoadError:页面加载失败
    • onUpdateVisitedHistory;更新访问的历史页面回调
    • onConsoleMessage:控制台消息,用于输出console.log信息

    使用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;
    
      
      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",
      );
    
      
      void initState() {
        // TODO: implement initState
        super.initState();
      }
    
      
      void dispose() {
        // TODO: implement dispose
        webViewController?.clearCache();
        super.dispose();
      }
    
      // 设置页面标题
      void setWebPageTitle(data) {
        if (widget.onWebTitleLoaded != null) {
          widget.onWebTitleLoaded!(data);
        }
      }
    
      // flutter调用H5方法
      void callJSMethod() {
        
      }
    
      
      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 {
                  // 允许路由替换
                  return NavigationActionPolicy.ALLOW;
                },
                onLoadStop: (controller, url) async {
    
                  // 加载完成
                  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,
                  ),
                ],
              ),
            ),
          ],
        );
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160

    三、小结

    flutter开发实战-webview插件flutter_inappwebview使用。描述可能不准确,请见谅。

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

    学习记录,每天不停进步。

  • 相关阅读:
    元宇宙 - NFT数字艺术品-数字藏品-对接好的BSN文昌链-主要功能介绍
    Codeforces Round #802(Div. 2)A~D
    【C语言】while((ch=getchar()!=EOF))相关问题详解(结束、安全)
    DAOS学习笔记及思考
    电脑重装系统后桌面图标如何调小尺寸
    栈和队列的概念和实现
    如何在Qt中使用boost库
    java毕业设计哈尔滨文旅信息网站(附源码、数据库)
    一文学会Set与Map以及集合类的使用选取,HashMap底层源码解析
    12-Hive的基本概念以及基本操作
  • 原文地址:https://blog.csdn.net/gloryFlow/article/details/133489866