flutter中使用webview
Posted 打静爵
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了flutter中使用webview相关的知识,希望对你有一定的参考价值。
首先要安装一个插件:flutter_webview_plugin
dependencies:
flutter_webview_plugin: ^0.2.1+2
使用方法:
new MaterialApp( routes: { "/": (_) => new WebviewScaffold( url: "https://www.google.com", appBar: new AppBar( title: new Text("Widget webview"), ), ) }, );
FlutterWebviewPlugin
插件提供一个链接到唯一webview的单一实例,这样你就可以在app中的任何地方控制webview,比如监听事件:
final flutterWebviewPlugin = new FlutterWebviewPlugin(); // 监听url地址改变事件 flutterWebviewPlugin.onUrlChanged.listen((String url) { });
// 监听页面滚动事件
final flutterWebviewPlugin = new FlutterWebviewPlugin(); flutterWebviewPlugin.onScrollYChanged.listen((double offsetY) { }); flutterWebviewPlugin.onScrollXChanged.listen((double offsetX) { });
隐藏webview:
final flutterWebviewPlugin = new FlutterWebviewPlugin(); flutterWebviewPlugin.launch(url, hidden: true);
关闭webview:
flutterWebviewPlugin.close();
画一个内部矩形webview:
final flutterWebviewPlugin = new FlutterWebviewPlugin(); flutterWebviewPlugin.launch(url, fullScreen: false, rect: new Rect.fromLTWH( 0.0, 0.0, MediaQuery.of(context).size.width, 300.0));
注意:webview并不存在于widget树中,所以你不能在webview中使用如snackbars, dialogs ...这些通知交互widget,更详细一些使用方法可以点击这里;
最后,这里是一个使用例子:
1 import ‘package:flutter/material.dart‘; 2 import ‘package:flutter_webview_plugin/flutter_webview_plugin.dart‘; 3 4 class WebViewExample extends StatefulWidget { 5 @override 6 _WebViewExampleState createState() => _WebViewExampleState(); 7 } 8 9 class _WebViewExampleState extends State<WebViewExample> { 10 TextEditingController controller = TextEditingController(); 11 FlutterWebviewPlugin flutterWebviewPlugin = FlutterWebviewPlugin(); 12 var urlString = "https://google.com"; 13 14 launchUrl() { 15 setState(() { 16 urlString = controller.text; 17 flutterWebviewPlugin.reloadUrl(urlString); 18 }); 19 } 20 21 @override 22 void initState() { 23 super.initState(); 24 25 flutterWebviewPlugin.onStateChanged.listen((WebViewStateChanged wvs) { 26 print(wvs.type); 27 }); 28 } 29 30 @override 31 Widget build(BuildContext context) { 32 return WebviewScaffold( 33 appBar: AppBar( 34 title: TextField( 35 autofocus: false, 36 controller: controller, 37 textInputAction: TextInputAction.go, 38 onSubmitted: (url) => launchUrl(), 39 style: TextStyle(color: Colors.white), 40 decoration: InputDecoration( 41 border: InputBorder.none, 42 hintText: "Enter Url Here", 43 hintStyle: TextStyle(color: Colors.white), 44 ), 45 ), 46 actions: <Widget>[ 47 IconButton( 48 icon: Icon(Icons.navigate_next), 49 onPressed: () => launchUrl(), 50 ) 51 ], 52 ), 53 url: urlString, 54 withZoom: false, 55 ); 56 } 57 }
以上是关于flutter中使用webview的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 flutter_webview 插件在 Flutter 中启用位置?
Flutter webview_flutter:无法使用 java 脚本代码检测平台