• Flutter:webview_flutter插件使用


    一、添加权限:

    1.Android网络权限(工程/android/app/src/main/AndroidManifest.xml):

    1. <manifest ...>
    2. ...
    3. <uses-permission android:name="android.permission.INTERNET"/>
    4. manifest>

    2.iOS添加使用说明(工程/ios/Runner/Info.plist):

    1. <dict>
    2. ...
    3. <key>io.flutter.embedded_views_previewkey>
    4. <string>YESstring>
    5. dict>

    二、使用WebView显示网页:

    1.添加webview_flutter插件依赖,在pubspec.yaml中:

    1. dependencies:
    2.   webview_flutter: ^3.0.4  #WebView插件

    2.使用WebView显示网页:

    1. class WebViewPage extends StatefulWidget { //网页显示界面
    2.   const WebViewPage({Key? key, required this.url}) : super(key: key); //外部传入URL
    3.   final String url;
    4.   @override
    5.   State createState() => _PageState();
    6. }
    7. class _PageState extends State<WebViewPage> {
    8.   late WebViewController _webControl; //WebView控制类
    9.   final CookieManager _cookieManager = CookieManager();
    10.   late double progress = 0.01;  //H5加载进度值
    11.   final double VISIBLE = 1;
    12.   final double GONE = 0;
    13.   late double progressHeight = GONE; //H5加载进度条高度
    14.   //显示或隐藏进度条
    15.   void setProgressVisible(double isVisible) {
    16.     setState(() {
    17.       progressHeight = isVisible;
    18.     });
    19.   }
    20.   @override
    21.   void initState() {
    22.     super.initState();
    23.     if (Platform.isAndroid)  WebView.platform = SurfaceAndroidWebView();  //android平台时使用SurfaceAndroidWebView
    24.   }
    25.   WebView _createWebView(){
    26.     return WebView( //WebView组件
    27.       initialUrl: widget.url,             //设置URL地址
    28.       javascriptMode: JavascriptMode.unrestricted,  //启用JS
    29.       onWebViewCreated: (WebViewController webControl) { //WebView创建时触发
    30.         _webControl = webControl;
    31.       },
    32.       javascriptChannels: {getJSChannel1(context), getJSChannel2(context)}, //添加JS方法(可以多个),实现与H5交互数据
    33.       navigationDelegate: (NavigationRequest request) { //控制页面是否进入下页
    34.         if (request.url.startsWith('http://www.yyh.com')) {
    35.           return NavigationDecision.prevent; //禁止跳下页
    36.         }
    37.         return NavigationDecision.navigate; //放行跳下页
    38.       },
    39.       onPageStarted: (String url) { //H5页面开始加载时触发
    40.         setProgressVisible(VISIBLE); //显示加载进度条
    41.       },
    42.       onProgress: (int progress) { //加载H5页面时触发多次,progress值为0-100
    43.         this.progress = progress.toDouble() / 100.0;  //计算成0.0-1.0之间的值
    44.       },
    45.       onPageFinished: (String url) { //H5页面加载完成时触发
    46.         setProgressVisible(GONE); //隐藏加载进度条
    47.       },
    48.       gestureNavigationEnabled: true,  //启用手势
    49.     );
    50.   }
    51.   //添加JS方法1,与H5交互数据
    52.   JavascriptChannel getJSChannel1(BuildContext context) {
    53.     return JavascriptChannel(
    54.         name: 'jsMethodName1',  //方法名,与H5中的名称一致。H5中调用方式:js方法名1.postMessage("字符串");
    55.         onMessageReceived: (JavascriptMessage message) { //接收H5发过来的数据
    56.           String json = message.message;
    57.           print("H5发过来的数据1: $json");
    58.         });
    59.   }
    60.   //添加JS方法2,与H5交互数据
    61.   JavascriptChannel getJSChannel2(BuildContext context) {
    62.     return JavascriptChannel(
    63.         name: 'jsMethodName2',
    64.         onMessageReceived: (JavascriptMessage message) {
    65.           String json = message.message;
    66.           print("H5发过来的数据2: $json");
    67.         });
    68.   }
    69.   @override
    70.   Widget build(BuildContext context) {
    71.     return WillPopScope(
    72.         onWillPop: () async {  //拦截页面返回事件
    73.           if (await _webControl.canGoBack()) {
    74.             _webControl.goBack(); //返回上个网页
    75.             return false;
    76.           }
    77.           return true; //退出当前页
    78.         },
    79.         child: Scaffold(
    80.             appBar: AppBar(title: const Text('WebView使用')),
    81.             body: Stack(
    82.               children: [
    83.                 _createWebView(), //WebView
    84.                 SizedBox(        //进度条
    85.                     height: progressHeight,
    86.                     child: LinearProgressIndicator(
    87.                       backgroundColor: Colors.white,
    88.                       valueColor: AlwaysStoppedAnimation(Colors.yellow),
    89.                       value: progress, //当前加载进度值
    90.                     ))
    91.               ],
    92.             )));
    93.   }
    94. }

    三、WebView常用方法:

    1.加载Html的几种方式:

    (1)加载Html字符串:

    1. String htmlString = '''
    2. Navigation Delegate Example
    3. 加载Html内容
    4. ''';

    方式1:

    1. Future<void> loadHtmlString1() async {
    2.   String content = base64Encode(const Utf8Encoder().convert(htmlString));
    3.   await _webControl.loadUrl('data:text/html;base64,$content');
    4. }

    方式2:

    1. Future<void> loadHtmlString2() async {
    2.   await _webControl.loadHtmlString(htmlString);
    3. }

    (2)加载Html文件:

    资源文件方式:

    1. Future<void> loadHtmlFile1() async {
    2.   await _webControl.loadFlutterAsset('assets/www/index.html');
    3. }

    File方式:

    1. Future<void> loadHtmlFile2() async {
    2. String dir = (await getTemporaryDirectory()).path;
    3. File file = File(<String>{dir, 'www', 'index.html'}.join(Platform.pathSeparator));
    4. await file.create(recursive: true);
    5. String filePath = file.path;
    6. await file.writeAsString(htmlString); //将html字符串写入文件
    7. await _webControl.loadFile(filePath); //加载html文件
    8. }

    (3)加载HTTP请求:

    1. Future<void> loadHttpRequest(String url, String json) async {
    2. final WebViewRequest request = WebViewRequest(
    3. uri: Uri.parse(url), //设置URL
    4. method: WebViewRequestMethod.post, //设置请求方式,post或get请求
    5. headers: <String, String>{'Content-Type': 'application/json'}, //请求头字段
    6. body: Uint8List.fromList(json.codeUnits), //请求参数
    7. );
    8. await _webControl.loadRequest(request); //加载HTTP请求
    9. }

    2.运行JS代码:

    1. Future<void> runJSCode() async { //运行JS代码,模拟H5与Flutter交互数据
    2. await _webControl.runJavascript('jsMethodName1.postMessage("字符串");'); //此处模拟调用Flutter中定义的JS方法
    3. }

    3.Cookie添加/获取/清空:

    1. //添加cookie
    2. Future<void> addCookie() async {
    3. await _cookieManager.setCookie(const WebViewCookie(name: 'key1', value: 'value1', domain: 'url域名', path: '/路径'));
    4. }
    5. //获取cookie列表
    6. Future<List<String>> getCookieList() async {
    7. String cookies = await _webControl.runJavascriptReturningResult('document.cookie');
    8. if (cookies == null || cookies == '""') <String>[];
    9. return cookies.split(';'); //获取cookie列表
    10. }
    11. //清空cookie
    12. Future<void> clearCookies(BuildContext context) async {
    13. await _cookieManager.clearCookies();
    14. }

    4.缓存对象添加/获取/清空:

    1. //添加缓存对象
    2. Future<void> addCache() async {//caches.open()创建缓存对象, 存在时不创建
    3. await _webControl.runJavascript('caches.open("缓存对象名"); localStorage["key1"] = "value1";');
    4. }
    5. //获取缓存对象
    6. Future<void> getCacheList() async {
    7. await _webControl.runJavascript('caches.keys()'
    8. '.then((cacheKeys) => JSON.stringify({"cacheKeys" : cacheKeys, "localStorage" : localStorage}))'
    9. '.then((caches) => jsMethodName1.postMessage(caches))'); //获取H5缓存对象,调用定义的JS方法发给Flutter
    10. }
    11. //清空缓存对象
    12. Future<void> clearCache() async {
    13. await _webControl.clearCache();
    14. }
  • 相关阅读:
    js逆向基础篇-某音乐网站-xx音乐
    助力服务智能医疗检测,基于yolov5开发构建结直肠息肉检测系统,实践训练n/s/m不同量级模型,对比性能结果
    TCP 拥塞控制
    基于51单片机的温度甲烷监测报警串口上报proteus仿真原理图PCB
    【Kubernetes 系列】K8S 进阶 万字讲述 Windows HostProcess 运行容器化负载
    国庆作业 day 10.1
    leetcode19-删除链表的倒数第n个结点
    Day 58 django 视图层 模板层
    Xmake v2.8.3 发布,改进 Wasm 并支持 Xmake 源码调试
    神经网络中常见的超参数,神经网络参数个数计算
  • 原文地址:https://blog.csdn.net/a526001650a/article/details/127786060