亲宝软件园·资讯

展开

Flutter webview与网页通讯

我也还在想 人气:0

前言

在app开发中我们有JSBridge来实现app和网页端通讯,现参考JSBridge实现了Flutter webview和网页端通讯。

预览

flutter

import 'package:ds_bridge/ds_bridge.dart';
class JsBridgeUtil {
  // 向H5调用接口
  static executeMethod(flutterWebViewPlugin, String jsonStr) async{
    DsBridge dsBridge = DsBridge(flutterWebViewPlugin);
    Result result = dsBridge.dispatch(jsonStr);
    if(result.method == 'share'){
      result.callBack('收到网页端share事件,内容为${result.data}并返回此文本给网页');
    }
    if(result.method == 'share1'){
      result.callBack('收到网页端share1事件');
    }
  }
}

网页

import 'dsbridge_flutter'
dsBridge.call('share', { name: 'woyehaizaixiang' }, function (res) {
  alert(res)
})

具体实现

flutter中使用ds_bridge

此包是flutter_webview_pluginwebview与网页交互的工具包,需要先添加flutter_webview_plugin组件,具体flutter_webview_plugin组件使用请前往官网查看 ,在添加flutter_webview_plugin组件后,添加ds_bridge组件

1.配置依赖包

dependencies:
    ds_bridge: ^0.0.1

2.在webview页面添加JavascriptChannel

webview.dart

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:yundk_app/routes/application.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';
import '../../utils/JsBridgeUtil.dart';

class WebviewPage extends StatefulWidget {
  final String url;
  final VoidCallback backCallback;

  WebviewPage({
    Key key,
    @required this.url,
    this.backCallback,
  }) : super(key: key);

  @override
  _WebviewPageState createState() => _WebviewPageState();
}

class _WebviewPageState extends State<WebviewPage> {
  String _title = '';
  final flutterWebViewPlugin = FlutterWebviewPlugin();
  final Set<JavascriptChannel> jsChannels = [
    JavascriptChannel(
        name: 'DsBridgeApp',
        onMessageReceived: (JavascriptMessage msg) {
          String jsonStr = msg.message;
          JsBridgeUtil.executeMethod(FlutterWebviewPlugin(), jsonStr);
        }),
  ].toSet();

  StreamSubscription<String> _onUrlChanged;

  @override
  void initState() {
    super.initState();
    flutterWebViewPlugin.close();

    // 监听 url changed
    _onUrlChanged =
    flutterWebViewPlugin.onUrlChanged.listen((String url) async {

    });

    // 监听页面onload
    flutterWebViewPlugin.onStateChanged.listen((viewState) async {
      if (viewState.type == WebViewState.finishLoad) {
        flutterWebViewPlugin.evalJavascript('document.title').then((result) => {
          setState(() {
            _title = result;
          })
        });
      }
    });

  }

  @override
  void dispose() {
    _onUrlChanged.cancel();
    flutterWebViewPlugin.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: WebviewScaffold(
        appBar: new AppBar(
          leading: IconButton(
            hoverColor: Colors.transparent,
            highlightColor: Colors.transparent,
            icon: Icon(const IconData(0xe61b, fontFamily: 'IconFont'), color: Color(0xff333333), size: 18),
            onPressed: (){
              flutterWebViewPlugin.close();
              Application.router.pop(context);
            },
          ),
          title: new Text(
            _title,
            style: TextStyle(color: Color(0xff333333), fontSize: 17),
          ),
          actions: [
            new IconButton(
              icon: new Icon(
                Icons.refresh_outlined,
                color: Color(0xff333333),
                size: 20
              ),
              onPressed: () {
                flutterWebViewPlugin.reload();
              }
            ),
          ],
          centerTitle: true,
          elevation: 0,
        ),
        url: widget.url,
        javascriptChannels: jsChannels,
        mediaPlaybackRequiresUserGesture: false,
        withZoom: true,
        withLocalStorage: true,
        hidden: true,
      )
    );
  }
}

3.在JsBridgeUtil类中

utils/JsBridgeUtil.dart

import 'package:ds_bridge/ds_bridge.dart';
class JsBridgeUtil {
  // 向H5调用接口
  static executeMethod(flutterWebViewPlugin, String jsonStr) async{
    DsBridge dsBridge = DsBridge(flutterWebViewPlugin);
    Result result = dsBridge.dispatch(jsonStr);
    if(result.method == 'share'){
      result.callBack('收到网页端share事件,内容为${result.data}并返回此文本给网页');
    }
    if(result.method == 'share1'){
      result.callBack('收到网页端share1事件');
    }
  }
}

网页端使用dsbridge_flutter

此插件为网页端插件,配合flutter端ds_bridge一起使用

1.安装

npm install dsbridge_flutter

2.使用

import 'dsbridge_flutter'
dsBridge.call(<String> method, <Object> data, <Function> callback)

3.例子

import 'dsbridge_flutter'
dsBridge.call('share', { name: 'woyehaizaixiang' }, function (res) {
  alert(res)
})

总结

本文参考JSBridge实现了Flutter webview和网页端交互。具体用到的插件有Flutter端flutter_webview_pluginds_bridge、网页端有dsbridge_flutter

加载全部内容

相关教程
猜你喜欢
用户评论