在 Flutter 中使用 webview_flutter 插件加载网页,需遵循以下步骤:
1. 添加依赖
在 pubspec.yaml 文件中添加依赖:
dependencies:
webview_flutter: ^4.4.2
运行 flutter pub get 安装。
2. 配置平台权限
3. 基本使用
导入包并创建 WebView:
import 'package:webview_flutter/webview_flutter.dart';
class WebViewExample extends StatefulWidget {
@override
_WebViewExampleState createState() => _WebViewExampleState();
}
class _WebViewExampleState extends State<WebViewExample> {
late final WebViewController controller;
@override
void initState() {
super.initState();
controller = WebViewController()
..setJavaScriptMode(JavaScriptMode.unrestricted)
..loadRequest(Uri.parse('https://flutter.dev'));
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('WebView Example')),
body: WebViewWidget(controller: controller),
);
}
}
4. 常用功能
- 启用 JavaScript:
..setJavaScriptMode(JavaScriptMode.unrestricted)
- 拦截导航:
..setNavigationDelegate(NavigationDelegate(
onNavigationRequest: (request) {
if (request.url.startsWith('https://禁止的域名')) {
return NavigationDecision.prevent; // 阻止加载
}
return NavigationDecision.navigate; // 允许加载
},
))
- 加载本地 HTML:
..loadHtmlString('<html><body><h1>Flutter WebView</h1></body></html>')
5. 注意事项
- Android 混合内容:若加载 HTTP 内容,需在
AndroidManifest.xml 中配置 android:usesCleartextTraffic="true"。
- iOS 平台限制:部分高级功能需额外配置。
- 控制器生命周期:通过
WebViewController 管理页面加载、前进/后退等操作。
通过以上步骤,即可在 Flutter 应用中正确集成 WebView 并实现基本网页加载功能。