1.本文主要涉及兩個知識點:1. JS 與Flutter 交互 2.Flutter Web 項目與原生交互(通過flutter 的dart.js 調用 js 然后由js進行調用原生,至於js與原生交互請自行百度)
說明:Flutter 調用JS 需要 import dart.js 作為支持,如果項目中一旦導入 dart.js 項目則無法運行打包App 了
提示:flutter 的 callMethod只能支持參數是string 或者number類型的
flutter 代碼如下:
import 'package:flutter/material.dart'; import 'dart:js' as js; /** * 參考 * https://www.it610.com/article/1280448506485555200.htm * 官方給開發者提供了js與dart交互的api: * https://api.flutter.dev/flutter/dart-js/dart-js-library.html */ class JSHomePage extends StatefulWidget { JSHomePage({Key key, this.title}) : super(key: key); final String title; @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State<JSHomePage> { /** * 調用js */ void _callJS() { js.context.callMethod("alert"); } /** * 調用js */ void _jsCallFlutter() { // 等於js調用:flutter.flutterMoth(); js.context .callMethod("flutterMethod",[""]); } /** * 調用js並且傳遞參數 */ void _callJSAndParameter() { //等於js調用: alert("我是來自dart的方法"); js.context.callMethod("alert",["我是來自dart的方法"]); } /** * 調用js傳參數返回數據 */ void _callJSAndParameterAndReturn() { //等於js調用:var a = Math.pow(3,4); var callMethod = js.context["Math"].callMethod("pow",[3,4]); js.context.callMethod("alert",[callMethod.toString()]); print("普通調用"+callMethod.toString()); } /*這里需要webView注冊 *JavascriptInterface 名為Obtain,並提供getA方法 * 詳細使用請百度android與js交互 */ void getNativeProperty(){ //等於js調用:Obtain。getA() var text= js.context["obtain"].callMethod("getProperty" ,["賬號信息"] ); js.context.callMethod("alert",[text.toString()]); } /** * 調用日志,這里其實不必用這個了,因為fltter print,就等價於這個 */ void jsConsoleLog(){ //等於調用js: console.log("我是dart 打印的js日志") js.context['console'] .callMethod("log",["我是dart 打印的js日志"] ); } /** * flutter方法用於讓js調用 */ void flutterMethod( ){ js.context.callMethod("alert",["我來自flutter"]); print("高級調用js調用flutter"); } @override Widget build(BuildContext context) { js.context["flutterMethod"]=flutterMethod; return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ RaisedButton(child: Text( '呼叫js', ),onPressed: _callJS,) , RaisedButton(child: Text( '呼叫js並傳參數', ),onPressed: _callJSAndParameter) , RaisedButton(child: Text( '呼叫js傳參數並返回數據', ),onPressed: _callJSAndParameterAndReturn) , RaisedButton(child: Text( 'js打印日志', ),onPressed: jsConsoleLog) , RaisedButton(child: Text( 'js 呼叫Flutter', ),onPressed: _jsCallFlutter) , RaisedButton(child: Text( '獲取原生數據(需要客戶端支持)', ),onPressed: getNativeProperty) ], ), ), ); } }
andoid 原生需要支持的代碼如下 (以下代碼是kotlin語言):
baseweb_webview.addJavascriptInterface(object:IWebObtain{ @JavascriptInterface override fun getProperty(key:String): String { when (key) { "賬號信息" -> { return "我來自Andorid賬號信息" } else -> { return "我來自Andorid" } } } }, "obtain")