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

这篇具有很好参考价值的文章主要介绍了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来加载网页。

inappwebview,移动开发,flutter开发实战,flutter,flutter,inappwebview,HTML5,webview

一、引入flutter_inappwebview

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

  # 浏览器
  flutter_inappwebview: 5.4.3+7

二、使用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});
}

列一下常用的几个

  • 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,
              ),
            ],
          ),
        ),
      ],
    );
  }
}

三、小结

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

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

学习记录,每天不停进步。文章来源地址https://www.toymoban.com/news/detail-729438.html

到了这里,关于flutter开发实战-webview插件flutter_inappwebview使用的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • flutter开发实战-webview自定义标题栏Appbar

    flutter开发实战-webview定义标题栏Appbar 在开发中,使用到webview,在之前实现webview使用,webview页面使用的时自定义标题栏,在上一个webview结合JsBridge实现交互忘记这个标题栏,这里记录一下。 flutter开发实战-webview定义标题栏Appbar,PreferredSizeWidget webview页面使用的时自定义标题

    2024年02月16日
    浏览(28)
  • flutter开发实战-实现webview与Javascript通信JSBridge

    flutter开发实战-实现webview与H5中Javascript通信JSBridge 在开发中,使用到webview,flutter实现webview是使用原生的插件实现,常用的有webview_flutter与flutter_inappwebview 这里使用的是webview_flutter,在iOS上,WebView小部件由WKWebView支持。在Android上,WebView小部件由WebView支持。 这里使用的是w

    2024年02月14日
    浏览(27)
  • flutter开发实战-指纹、面容ID验证插件实现

    flutter开发实战-指纹、面容ID验证插件实现 在iOS开发中,经常出现需要指纹、面容ID验证的功能。 指纹、面容ID是一种基于用生物识别技术,通过扫描用户的面部特征来验证用户身份。 在iOS中实现指纹、面容ID验证功能,步骤如下 2.1 info.plist配置 在info.plist中配置允许访问FAC

    2024年02月13日
    浏览(34)
  • flutter开发实战-video_player插件播放抖音直播实现(仅限Android端)

    flutter开发实战-video_player插件播放抖音直播实现(仅限Android端) 在之前的开发过程中,遇到video_player播放视频,通过查看video_player插件描述,可以看到video_player在Android端使用exoplayer,在iOS端使用的是AVPlayer。由于iOS的AVPlayer不支持flv、m3u8格式的直播,这里video_player播放抖音直

    2024年02月05日
    浏览(30)
  • 【VS Code插件开发】Webview面板(三)

    🐱 个人主页: 不叫猫先生 ,公众号: 前端舵手 🙋‍♂️ 作者简介:前端领域优质作者、阿里云专家博主,共同学习共同进步,一起加油呀! 📢 资料领取:前端进阶资料可以找我免费领取 🔥 摸鱼学习交流: 我们的宗旨是在「工作中摸鱼,摸鱼中进步」,期待大佬一起

    2024年02月12日
    浏览(28)
  • Flutter系列文章-Flutter 插件开发

    在本篇文章中,我们将学习如何开发 Flutter 插件,实现 Flutter 与原生平台的交互。我们将详细介绍插件的开发过程,包括如何创建插件项目、实现方法通信、处理异步任务等。最后,我们还将演示如何将插件打包并发布到 Flutter 社区。 在 Flutter 项目中,你可能需要与原生平台

    2024年02月11日
    浏览(24)
  • Flutter插件开发-(进阶篇)

    一、概述 Flutter也有自己的Dart Packages仓库。 插件的开发和复用能够提高开发效率,降低工程的耦合度 ,像网络请求(http)、用户授权(permission_handler)等客户端开发常用的功能模块,我们只需要引入对应插件就可以为项目快速集成相关能力,从而专注于具体业务功能的实现。 除

    2024年02月08日
    浏览(25)
  • Flutter 插件开发遇到的问题及解决方案

    本文主要对笔者flutter插件开发过程中如下问题做了解决。 一、Flutter插件android模块中的代码报红问题解决 二、Flutter Plugin 开发中引入本地 aar 包报错的问题。 三、Flutter插件项目中获取到 Activity 1、在开发Flutter插件时,打开插件的android项目,准备编写native端的代码时,发现各

    2024年02月20日
    浏览(33)
  • Flutter开发笔记 —— sqflite插件数据库应用

    今天在观阅掘金大佬文章的时候,了解到了该 sqflite 插件,结合官网教程和自己实践,由此总结出该文,希望对大家的学习有帮助! Flutter的 SQLite 插件。支持 iOS、Android 和 MacOS。 支持事务和batch模式 打开时自动进行版本管理 插入/查询/更新/删除查询的助手 iOS 和 Android 上的

    2024年02月04日
    浏览(41)
  • flutter开发 - 七牛云上传sdk插件qiniu_flutter_sdk使用

    flutter七牛云上传sdk插件qiniu_flutter_sdk使用 最近在拆分代码,将上传组件设置成插件,下面记录下实现过程。 一、创建flutter_plugin上传插件 这里Android Studio使用创建plugin 填写一下信息 Project name Project location Description Project type Organization Android Language iOS Language Platforms 二、代码实

    2024年02月10日
    浏览(29)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包