lib\inserted_web_seven\tell_to_ai\my_summary\webview_flutter_wkwebview_3.17.0_guide.txt
==================================================
==================================================
iOS/macOS平台的Flutter WebView实现组件,基于WKWebView提供:
==================================================
==================================================
// 注册JS通信通道
controller.addJavaScriptChannel('Payment', (message) {
handlePayment(message.message);
});
// 加载远程URL
controller.loadRequest(Uri.parse('https://news.example.com'));
// 设置Cookie认证
cookieManager.setCookie(WebViewCookie(
name: 'auth_token',
value: 'xxxx',
domain: '.company.com'
));
==================================================
WebKitWebViewControllerCreationParams(
allowsInlineMediaPlayback: true, // 内联媒体播放
mediaTypesRequiringUserAction: {PlaybackMediaTypes.video} // 视频需交互
)
controller.setNavigationDelegate(NavigationDelegate(
onNavigationRequest: (request) =>
request.url.contains('ads')
? NavigationDecision.prevent
: NavigationDecision.navigate
));
// 证书校验(原生实现)
- (void)webView:(WKWebView *)webView
didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential *))handler {
// 处理逻辑
}
==================================================
1:初始化控制器
2:配置参数
3:注册通信通道
4:设置导航代理
5:加载内容
6:处理交互
7:优化调试
流程图文本描述:
初始化->配置->通信设置->加载内容->交互处理->性能优化
==================================================
if (kDebugMode) {
WebViewController.setWebContentsDebuggingEnabled(true);
}
final metrics = await controller.getPerformanceMetrics();
print('资源加载耗时: ${metrics[PerformanceMetric.resourceTiming]}');
==================================================
1必须启用混合渲染:
WebViewWidget(
creationParams: WebKitWebViewWidgetCreationParams(
displayWithHybridComposition: true
)
)
2内存管理:
void dispose() {
controller.dispose();
super.dispose();
}
3文件上传适配方案:
// 实现WKFileUploadPanelDelegate协议处理iOS文件选择
==================================================
一、核心作用
webview_flutter_wkwebview 是 Flutter 官方提供的 iOS/macOS 平台 WebView 实现插件,基于苹果的 WKWebView 组件,用于在 Flutter 应用中嵌入高性能、安全的网页渲染容器。主要功能包括:
加载本地或远程 HTML/CSS/JavaScript 内容
支持现代 Web 标准(如 WebGL、WebAssembly)
提供原生与 Web 的双向通信能力
实现页面导航控制、缓存管理、安全策略等
场景类型 | 具体案例 | 技术需求 | 代码示例 |
---|---|---|---|
混合开发 | 应用中嵌入第三方支付页面、地图服务 | JavaScript 通信、导航拦截 | controller.addJavaScriptChannel('Payment', onMessageReceived) |
动态内容 | 展示实时更新的新闻/商品详情页 | 远程 URL 加载、缓存优化 | controller.loadRequest(Uri.parse('https://example.com')) |
企业应用 | 内网 OA 系统、数据可视化大屏 | Cookie 认证、安全策略 | cookieManager.setCookie(WebViewCookie(...)) |
跨平台组件 | 复用已有的 Web 前端组件(如视频播放器) | 内联媒体播放、手势支持 | allowsInlineMediaPlayback: true |
调试工具 | 应用内 Web 开发者工具 | 远程调试、性能监控 | WebViewController.setWebContentsDebuggingEnabled(true) |
二、适用场景
场景类型 具体案例 技术需求
混合开发 应用中嵌入第三方支付页面、地图服务 JavaScript 通信、导航拦截
动态内容 展示实时更新的新闻/商品详情页 远程 URL 加载、缓存优化
企业应用 内网 OA 系统、数据可视化大屏 Cookie 认证、安全策略
跨平台组件 复用已有的 Web 前端组件(如视频播放器) 内联媒体播放、手势支持
调试工具 应用内 Web 开发者工具 远程调试、性能监控
三、关键配置参数
参数名 | 类型 | 默认值 | 作用 | 代码示例 |
---|---|---|---|---|
allowsInlineMediaPlayback |
bool |
true |
允许视频内联播放(非全屏) | allowsInlineMediaPlayback: true |
mediaTypesRequiringUserAction |
Set |
{} |
需用户交互的媒体类型(audio /video /all ) |
mediaTypesRequiringUserAction: {PlaybackMediaTypes.video} |
参数名 | 类型 | 说明 | 代码示例 |
---|---|---|---|
allowsBackForwardNavigationGestures |
bool |
启用/禁用左右滑动手势导航 | allowsBackForwardNavigationGestures: true |
navigationDelegate |
NavigationDelegate |
拦截处理页面跳转请求 | controller.setNavigationDelegate(delegate) |
参数名 | 类型 | 功能 | 代码示例 |
---|---|---|---|
contentMode |
WKContentMode |
移动端/桌面端渲染模式 | contentMode: WKContentMode.mobile |
credential |
URLCredential |
HTTPS 证书认证配置 | credential: URLCredential(...) |
参数名 | 类型 | 说明 | 代码示例 |
---|---|---|---|
cacheMode |
CacheMode |
缓存策略(noCache /loadElseNetwork 等) |
cacheMode: CacheMode.loadElseNetwork |
preloadPages |
List |
预加载 URL 列表 | preloadPages: ['https://example.com/page1'] |
三、关键配置参数
1. 基础配置
参数 类型 默认值 作用
allowsInlineMediaPlayback bool true 允许视频内联播放(非全屏)
mediaTypesRequiringUserAction Set<PlaybackMediaTypes> {} 需用户交互的媒体类型(audio/video/all)
2. 导航控制
参数 类型 说明
allowsBackForwardNavigationGestures bool 启用/禁用左右滑动手势导航
navigationDelegate NavigationDelegate 拦截处理页面跳转请求
3. 安全策略
参数 类型 功能
contentMode WKContentMode 移动端/桌面端渲染模式
credential URLCredential HTTPS 证书认证配置
4. 性能优化
参数 类型 说明
cacheMode CacheMode 缓存策略(noCache/loadElseNetwork 等)
preloadPages List<String> 预加载 URL 列表
四、典型应用流程
final controller = WebKitWebViewController()
..setAllowsInlineMediaPlayback(true)
..setMediaTypesRequiringUserAction({PlaybackMediaTypes.video});
// 注册 JS 通道
controller.addJavaScriptChannel('Scanner', (message) {
final result = scanBarcode();
controller.evaluateJavascript('onScan("$result")');
});
// 注入 JS 脚本
controller.injectJavascriptFile(
assetPath: 'assets/custom.js',
injectionTime: UserScriptInjectionTime.atDocumentStart
);
controller.setNavigationDelegate(NavigationDelegate(
onNavigationRequest: (request) {
if (request.url.contains('blocked-domain.com')) {
return NavigationDecision.prevent;
}
return NavigationDecision.navigate;
}
));
// 原生层实现证书校验
- (void)webView:(WKWebView *)webView
didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler {
if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
} else {
completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
}
}
// 配置缓存
controller.setCacheMode(
cacheMode: CacheMode.loadElseNetwork,
maxCacheSize: 200 * 1024 * 1024, // 200MB
);
// 预加载关键资源
controller.loadRequest(Uri.parse('https://example.com/static/main.css'));
// 启用远程调试
if (kDebugMode) {
WebViewController.setWebContentsDebuggingEnabled(true);
}
// 采集性能指标
final metrics = await controller.getPerformanceMetrics();
debugPrint('DOM加载耗时: ${metrics[PerformanceMetric.domContentLoaded]}ms');
五、注意事项
混合渲染模式
必须设置 displayWithHybridComposition: true 以避免 iOS 15+ 的渲染异常:
WebViewWidget(
creationParams: WebKitWebViewWidgetCreationParams(
displayWithHybridComposition: true,
),
)
平台限制
iOS 11.0+ / macOS 10.13+ 强制使用 WKWebView
文件上传需处理 WKFileUploadPanel 的权限问题
内存管理
在 dispose() 中需手动释放资源:
void dispose() {
controller.clearCache();
controller.dispose();
super.dispose();
}
此总结涵盖了该包的核心功能、配置要点及实际开发中的关键流程,可作为快速集成参考。
lib\inserted_web_seven\tell_to_ai\my_summary\webview_flutter_wkwebview_3.17.0_docs.txt
==================================================
==================================================
iOS 平台原生 API 访问入口类
◆ 功能说明:
◆ 构造函数:
Objective-C:
@import webview_flutter_wkwebview;
FWFWebViewFlutterWKWebViewExternalAPI *api = [FWFWebViewFlutterWKWebViewExternalAPI sharedInstance];
方法签名 | 参数类型 | 返回值类型 | 功能描述 | 代码示例 |
---|---|---|---|---|
webViewForIdentifier: |
NSNumber* |
WKWebView* |
根据 Flutter 视图ID获取对应的原生 WKWebView 实例 | [api webViewForIdentifier:@(viewId)] |
◆ 关键方法:
方法签名 参数 返回值 功能描述
webViewForIdentifier: NSNumber* (Flutter视图ID) WKWebView* 根据 Flutter 视图ID获取对应的原生 WKWebView 实例
◆ 构造函数:
const WebKitWebViewControllerCreationParams({
bool allowsInlineMediaPlayback = true,
Set<PlaybackMediaTypes> mediaTypesRequiringUserAction = const {},
// 其他平台特有参数...
});
参数名 | 类型 | 默认值 | 描述 | 代码示例 |
---|---|---|---|---|
allowsInlineMediaPlayback |
bool |
true |
是否允许内联媒体播放 | allowsInlineMediaPlayback: true |
mediaTypesRequiringUserAction |
Set |
空集合 | 需要用户交互的媒体类型 | mediaTypesRequiringUserAction: {PlaybackMediaTypes.video} |
◆ 参数说明:
参数名 类型 默认值 描述
allowsInlineMediaPlayback bool true 是否允许内联媒体播放
mediaTypesRequiringUserAction Set<PlaybackMediaTypes> 空集合 需要用户交互的媒体类型
WebKitWebViewController.fromPlatformCreationParams(
WebKitWebViewControllerCreationParams params
)
◆ 主要方法:
方法签名 参数 功能描述
setUIDelegate WKUIDelegate 设置原生 WKUIDelegate
setNavigationDelegate WKNavigationDelegate 设置原生 WKNavigationDelegate
方法签名 | 参数类型 | 功能描述 | 代码示例 |
---|---|---|---|
setUIDelegate |
WKUIDelegate |
设置原生 WKUIDelegate | controller.setUIDelegate(delegate) |
setNavigationDelegate |
WKNavigationDelegate |
设置原生 WKNavigationDelegate | controller.setNavigationDelegate(delegate) |
◆ 枚举值:
enum PlaybackMediaTypes {
all, // 所有媒体类型
audio, // 音频
video, // 视频
}
◆ Dart 枚举:
enum UserScriptInjectionTime {
atDocumentStart, // 文档加载开始时注入
atDocumentEnd, // 文档加载结束时注入
}
◆ 对应原生枚举:
typedef NS_ENUM(NSInteger, WKUserScriptInjectionTime) {
WKUserScriptInjectionTimeAtDocumentStart,
WKUserScriptInjectionTimeAtDocumentEnd
};
==================================================
controller.addJavaScriptChannel(
'NativeBridge',
onMessageReceived: (JavaScriptMessage message) {
print('收到JS消息: ${message.message}');
}
);
◆ 原生层实现:
// 对应 WKScriptMessageHandler 实现
- (void)userContentController:(WKUserContentController *)userContentController
didReceiveScriptMessage:(WKScriptMessage *)message {
[FWFWebViewFlutterWKWebViewExternalAPI.sharedInstance
postMessage:message.body
forChannel:message.name];
}
controller.setNavigationDelegate(NavigationDelegate(
onNavigationRequest: (request) {
if (request.url.contains('blocked.com')) {
return NavigationDecision.prevent;
}
return NavigationDecision.navigate;
},
));
◆ 原生层映射:
// 对应 WKNavigationDelegate 的
// -webView:decidePolicyForNavigationAction:decisionHandler: 实现
==================================================
◆ 关键配置:
WebViewWidget(
controller: controller,
creationParams: WebKitWebViewWidgetCreationParams(
displayWithHybridComposition: true,
),
)
```dart
2. 安全策略
◆ Cookie 管理:
```dart
final cookieManager = WebViewCookieManager();
await cookieManager.setCookie(
WebViewCookie(
name: 'session',
value: '123',
domain: 'example.com',
path: '/',
httpOnly: true,
)
);
◆ 证书校验:
通过实现 WKNavigationDelegate 的
-webView:didReceiveAuthenticationChallenge:completionHandler: 方法
==================================================
controller.setCacheMode(
cacheMode: CacheMode.loadElseNetwork,
maxCacheSize: 100 * 1024 * 1024, // 100MB
);
controller.loadRequest(
Uri.parse('https://example.com'),
headers: {'Referer': 'https://mydomain.com'},
);
==================================================
if (kDebugMode) {
await WebViewController.setWebContentsDebuggingEnabled(true);
}
controller.enablePerformanceMetrics(
metrics: {
PerformanceMetric.navigationTiming,
PerformanceMetric.resourceTiming,
}
);
==================================================
平台 最低版本 推荐版本 关键依赖
iOS 11.0 14.0+ WKWebView
macOS 10.13 12.0+ WKWebView
注:本包为 webview_flutter 的 iOS/macOS 平台实现,需配合主包使用