[译]Flutter用WebView插件webview_flutter
本文翻译自pub: webview_flutter | Flutter Package (flutter-io.cn)
译时版本: webview_flutter 3.0.0
用于 Flutter 的 WebView
提供 WebView 组件的 Flutter 插件。
在 iOS 上 WebView 组件基于 WKWebView;在 Android 上 WebView 组件基于 WebView 。
用法
添加 webview_flutter
依赖到 pubspec.yaml 文件中。
如果目标平台是 Android,要确认阅读下面的 Android Platform Views 部分来选择最适合需要的平台 View 模式。
现在可以在组件树中加入 WebView 组件。查看 WebView 组件的文档了解更多如何使用该组件的内容。
Android Platform Views
该组件使用 Platform Views 在 Flutter 应用中嵌入 Android 的 webview 。它支持两种模式:hybrid composition (混合模式 - 现在默认) 和 virtual display (虚拟显示).
这两者之间选择时,这里有一些点可作考虑:
- Hybrid composition 内置了键盘支持,而virtual display 还有很多键盘的 issues 。
- Hybrid composition 需要 Android SDK 19+ ,而 virtual display 需要 Android SDK 20+ 。
- Hybrid composition 和 virtual display 有不同的 性能权衡.
使用 hybrid composition
该模式现在是默认可用。尽管如此,如果之前的版本低于19,也要确保在 android/app/build.gradle
中设置了正确的 minSdkVersion
。
android {
defaultConfig {
minSdkVersion 19
}
}
使用 virtual display
-
在
android/app/build.gradle
中设置正确的minSdkVersion
。(如果之前低于20):android { defaultConfig { minSdkVersion 20 } }
-
在
initState()
中设置WebView.platform = AndroidWebView();
。例如:import 'dart:io'; import 'package:webview_flutter/webview_flutter.dart'; class WebViewExample extends StatefulWidget { @override WebViewExampleState createState() => WebViewExampleState(); } class WebViewExampleState extends State<WebViewExample> { @override void initState() { super.initState(); // Enable virtual display. if (Platform.isAndroid) WebView.platform = AndroidWebView(); } @override Widget build(BuildContext context) { return WebView( initialUrl: 'https://flutter.cn', ); } }
在 Android 上使 Material Component 可用
要在 WebView 中的 输入元素和用户交互时使用 Material 组件,查看 Material Components 使用说明 中描述的步骤。
在 POST 请求中设置自定义头部
现在,在 Android 上 还不支持使用 WebViewController 的 loadRequest
在 请求时设置自定义头部。如果你需要这个功能,一个应变方法是手动创建请求,然后使用 loadHTMLString
加载响应数据。