flutter 封装webview和使用本地网页

news/2024/4/17 7:45:16

最先看到flutter_webview_plugin 用法特别简单

flutter_webview_plugin | Flutter PackagePlugin that allow Flutter to communicate with a native Webview.icon-default.png?t=N7T8https://pub-web.flutter-io.cn/packages/flutter_webview_plugin缺点: 没有实现js sdk的功能 没有办法 使用JavaScriptChannel 的功能

后面使用webview_flutter

webview_flutter | Flutter packageA Flutter plugin that provides a WebView widget on Android and iOS.icon-default.png?t=N7T8https://pub-web.flutter-io.cn/packages/webview_flutter组件

import 'dart:convert';
import 'dart:io';import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';class AppWebView extends StatefulWidget {final String url;final Function(dynamic)? onMessageReceived;const AppWebView({super.key,required this.url,this.onMessageReceived,});@overrideState<AppWebView> createState() => _AppWebViewState();
}class _AppWebViewState extends State<AppWebView> {late final WebViewController controller;int progress = 0;@overridevoid initState() {super.initState();controller = WebViewController()..setJavaScriptMode(JavaScriptMode.unrestricted)..addJavaScriptChannel("lh", onMessageReceived: onMessageReceived)..enableZoom(true)..setBackgroundColor(const Color(0x00000000))..setNavigationDelegate(NavigationDelegate(onProgress: (int progress) {// Update loading bar.this.progress = progress;setState(() {});},onPageStarted: (String url) {},onPageFinished: (String url) {},onWebResourceError: (WebResourceError error) {},onNavigationRequest: (NavigationRequest request) {if (request.url.startsWith('https://www.youtube.com/')) {return NavigationDecision.prevent;}return NavigationDecision.navigate;},),)..loadRequest(Uri.parse(widget.url));}// 接受h5发送来的数据onMessageReceived(message) async {widget.onMessageReceived?.call(message);//接收H5发过来的数据String sendMesStr = message.message;print("onMessageReceived sendMesStr:${sendMesStr}");Map<String, dynamic> msg = json.decode(sendMesStr);String method = msg["method"] ?? "";// Map<String, dynamic> data = msg["data"] ?? {};if (method.isNotEmpty) {switch (method) {case "back":controller.goBack();break;}}}@overrideWidget build(BuildContext context) {if (!kIsWeb && (Platform.isIOS || Platform.isAndroid)) {return Scaffold(// appBar: AppBar(title: const Text('Flutter Simple Example')),body: Stack(children: [WebViewWidget(controller: controller),if (progress != 100)const Center(child: CupertinoActivityIndicator(),)]),);} else {return const Center(child: Text('WebView control is not supported on this platform yet.'),);}}
}

使用

Get.to(() => AppWebView(url: 'http://localhost',onMessageReceived: onMessageReceived,
));

注意:需要重启项目才会生效

 

加载本地网页

String html =

    await rootBundle.loadString('assets/index.html');

String localHtmlFilePath = Uri.dataFromString(

  html,

  mimeType: 'text/html',

  encoding: Encoding.getByName('utf-8'),

).toString();

pubspec.yaml

  assets:

    - assets/index.html

使用

AppWebView(

  url: localHtmlFilePath,

   onMessageReceived: onMessageReceived,

)


https://www.xjx100.cn/news/3293539.html

相关文章

Android 接入指纹识别

接入指纹框架&#xff1a;https://github.com/Tencent/soter implementation com.github.Tencent.soter:soter-wrapper:2.0.91.Application中初始化 class IApplication : Application() {override fun onCreate() {super.onCreate()instance thisinitSort()}private fun in…

瑞_Redis_Redis命令

文章目录 1 Redis命令Redis数据结构Redis 的 key 的层级结构1.0 Redis通用命令1.0.1 KEYS1.0.2 DEL1.0.3 EXISTS1.0.4 EXPIRE1.0.5 TTL 1.1 String类型1.1.0 String类型的常见命令1.1.1 SET 和 GET1.1.2 MSET 和 MGET1.1.3 INCR和INCRBY和DECY1.1.4 SETNX1.1.5 SETEX 1.2 Hash类…

DAY9-防病毒AV概述

DNS过滤 URL过滤和DNS过滤对比

广和通发布基于MediaTek T300平台的RedCap模组FM330系列及解决方案

世界移动通信大会MWC 2024期间&#xff0c;广和通发布基于MediaTek T300平台的RedCap模组FM330系列&#xff0c;加速5G-A繁荣发展。FM330系列及其解决方案采用全球先进RedCap方案&#xff0c;满足移动宽带和工业互联对高能效的需求。 广和通FM330系列采用全球首款6nm制程且集成…

Java并发之线程池详解

(/≧▽≦)/~┴┴ 嗨~我叫小奥 ✨✨✨ &#x1f440;&#x1f440;&#x1f440; 个人博客&#xff1a;小奥的博客 &#x1f44d;&#x1f44d;&#x1f44d;&#xff1a;个人CSDN ⭐️⭐️⭐️&#xff1a;传送门 &#x1f379; 本人24应届生一枚&#xff0c;技术和水平有限&am…

网工内推 | Base北京,上市公司高级网工,最高25K,带薪年假

01 北京中天瑞合科技有限公司 招聘岗位&#xff1a;高级网络工程师 职责描述&#xff1a; 1、负责高校、医院、企业等数据中心、骨干网络、园区网等有线、无线网络架构的规划、设计、调整、性能优化&#xff0c;制定大、中型网络相关的安全策略和规范&#xff1b; 2、负责网络…

【机器人最短路径规划问题(栅格地图)】基于蚁群算法求解

基于蚁群算法求解机器人最短路径规划问题的仿真结果 仿真结果 收敛曲线变化趋势 蚁群算法求解最优解的机器人运动路径 各代蚂蚁求解机器人最短路径的运动轨迹

web组态软件

1、强大的画面显示web组态功能 2、良好的开放性。 开放性是指组态软件能与多种通信协议互联&#xff0c;支持多种硬件设备&#xff0c;向上能与管理层通信&#xff0c;实现上位机和下位机的双向通信。 3、丰富的功能模块。 web组态提供丰富的控制功能库&#xff0c;满足用户的测…