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

news/2025/3/28 11:06:22/

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

二、使用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 initStatesuper.initState();}void dispose() {// TODO: implement disposewebViewController?.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

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


http://www.ppmy.cn/news/1135164.html

相关文章

[React] 性能优化相关 (一)

文章目录 1.React.memo2.useMemo3.useCallback4.useTransition5.useDeferredValue 1.React.memo 当父组件被重新渲染的时候&#xff0c;也会触发子组件的重新渲染&#xff0c;这样就多出了无意义的性能开销。如果子组件的状态没有发生变化&#xff0c;则子组件是不需要被重新渲…

Django基础讲解-路由控制器和视图(Django-02)

一 路由控制器 参考链接&#xff1a; Django源码阅读&#xff1a;路由&#xff08;二&#xff09; - 知乎 Route路由, 是一种映射关系&#xff01;路由是把客户端请求的 url路径与视图进行绑定 映射的一种关系。 这个/timer通过路由控制器最终匹配到myapp.views中的视图函数 …

如何在Go中格式化字符串

由于字符串通常由书面文本组成&#xff0c;在很多情况下&#xff0c;我们可能希望通过标点符号、换行和缩进来更好地控制字符串的外观&#xff0c;以使其更易于阅读。 在本教程中&#xff0c;我们将介绍一些处理go字符串的方法&#xff0c;以确保所有输出文本的格式正确。 字…

MySQL-MVCC(Multi-Version Concurrency Control)

MySQL-MVCC&#xff08;Multi-Version Concurrency Control&#xff09; MVCC&#xff08;多版本并发控制&#xff09;&#xff1a;为了解决数据库并发读写和数据一致性的问题&#xff0c;是一种思想&#xff0c;可以有多种实现方式。 核心思想&#xff1a;写入时创建行的新版…

Linux命令(93)之head

linux命令之head 1.head介绍 linux命令head用来查看文件的前N行内容&#xff1b;默认head查看前10行 2.head用法 head [参数] 文件 head常用参数 参数说明-n从头显示N行&#xff0c;默认显示10行&#xff0c;可以不写-q隐藏文件名&#xff0c;在查看两个及以上文件名的情况…

RDB 做快照的时候数据能修改吗?

在 Redis 执行 RDB 快照(快照持久化)期间,Redis 主线程会阻塞,这意味着在快照持久化操作进行时,Redis 不能处理其他客户端的写入操作。因此,通常情况下,当 Redis 正在执行 RDB 快照时,不应该对数据进行修改。 在 RDB 快照过程中,Redis 主线程会按顺序遍历整个数据集,…

正确完成实时 AI

发表于 构建真实世界的实时 AI 一、说明 我们知道&#xff0c;当前的AI进展是扎根于历史数据&#xff0c;这就造成一个事实&#xff0c;模型总是赶不上实时进展&#xff0c;模型的洞察力不够尖锐&#xff0c;或者&#xff0c;时间损失等&#xff0c;本篇对这一系列AI的短板展开…

计算机网络 第一章计算机网络体系结构

非常好的课程。计算机网络 //----------------------------------------------------------------------------------------------------------------// 需要清楚实体、协议、服务。 网络协议三要素&#xff0c;语法、语义、同步。