flutter 封装webview和使用本地网页

最先看到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,
  });

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

使用

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,

)

  • 17
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

肥肥呀呀呀

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值