flutter 封装webview和使用本地网页

最先看到flutter_webview_plugin 用法特别简单

flutter_webview_plugin | Flutter PackagePlugin that allow Flutter to communicate with a native Webview.https://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.https://pub-web.flutter-io.cn/packages/webview_flutter组件

Dart 复制代码
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,
  });

  @override
  State<AppWebView> createState() => _AppWebViewState();
}

class _AppWebViewState extends State<AppWebView> {
  late final WebViewController controller;

  int progress = 0;

  @override
  void 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;
      }
    }
  }

  @override
  Widget 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.'),
      );
    }
  }
}

使用

Dart 复制代码
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,

)

相关推荐
饭小猿人8 小时前
Flutter实现底部动画弹窗有两种方式
开发语言·前端·flutter
liulian091611 小时前
Flutter 跨平台路由与状态管理:go_router 与 Riverpod 的 OpenHarmony总结
flutter·华为·学习方法·harmonyos
liulian091612 小时前
Flutter for OpenHarmony 跨平台技术实战:flutter_animate 与 pull_to_refresh 库的鸿蒙化适配总结
flutter·华为·学习方法·harmonyos
IntMainJhy13 小时前
【flutter for open harmony】第三方库 Flutter 二维码生成的鸿蒙化适配与实战指南
数据库·flutter·华为·sqlite·harmonyos
jiejiejiejie_14 小时前
Flutter for OpenHarmony 底部选项卡与多语言适配小记:让 App 更贴心的两次小升级✨
flutter·华为·harmonyos
jiejiejiejie_15 小时前
Flutter for OpenHarmony 应用更新检测与萌系搜索功能实战小记✨
flutter·华为·harmonyos
IntMainJhy15 小时前
Flutter 三方库 Firebase Messaging 鸿蒙化适配与实战指南(权限检查+设备Token获取全覆盖)
flutter·华为·harmonyos
liulian091616 小时前
Flutter 依赖注入与设备信息库:get_it 与 device_info_plus 的 OpenHarmony 适配指南总结
flutter·华为·学习方法·harmonyos
里欧跑得慢17 小时前
微交互设计模式:提升用户体验的细节之美
前端·css·flutter·web
stringwu17 小时前
Flutter GetX 核心坑及架构选型与可替换性方案
前端·flutter