【Flutter】Android原生WebView(非Flutter WebView)与FlutterWeb交互

发布时间:2023-06-17 09:00

原生WebView通过url来加载FlutterWeb项目。

注意分为两个项目,一个是Android原生项目,一个是FlutterWeb项目。Android原生通过WebView加载FlutterWeb项目

Android原生

以下内容在Android原生项目上更改。

  • 依赖

WebView使用DsBridge-Android,添加依赖如下:

implementation 'com.github.wendux:DSBridge-Android:3.0-SNAPSHOT'

项目级别build.gradle

maven { url 'https://jitpack.io' }
  • 布局

<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <data>

    data>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">
        <wendu.dsbridge.DWebView
            android:id="@+id/dWebView"
            android:layout_width="0dp"
            android:layout_height="0dp"
             app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintBottom_toBottomOf="parent"
            />

    androidx.constraintlayout.widget.ConstraintLayout>
layout>
  • MainActivity.kt
class MainActivity : AppCompatActivity() {

    var mBinding: ActivityMainBinding? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_main)

        mBinding?.btn?.setOnClickListener {
            val intent = Intent(this@MainActivity, MyFlutterActivity::class.java)
            startActivity(intent)
        }
        mBinding?.dWebView?.settings?.let {
            it.userAgentString = it.userAgentString + "winit"
            it.allowUniversalAccessFromFileURLs = true
            it.allowFileAccessFromFileURLs = true
            it.allowContentAccess = true
            it.allowFileAccess = true
            it.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
            it.javaScriptEnabled = true
        }
        val map: HashMap<String, String> = HashMap<String, String>()
        map.put("test", "ddddd")
        mBinding?.dWebView?.addJavascriptInterface(JsBridge(this),"test")
        mBinding?.dWebView?.loadUrl("http://10.199.17.135:8080/web/index.html", map)

    }
  • JsBridge
class JsBridge(val context: Context) {

    @JavascriptInterface
    fun hello(msg: String?): String {
        println("test")
        Toast.makeText(context, "test$msg", Toast.LENGTH_SHORT).show()
        return "Android native test"
    }
}

FlutterWeb

以下内容在FlutterWeb上更改

  • 编写js代码
    【Flutter】Android原生WebView(非Flutter WebView)与FlutterWeb交互_第1张图片
function flutterGetJs(text){
    //test为客户端传递过来的namespace,hello为客户端的方法
    var result = test.hello("js调用了android中的hello方法");
    return result;
}
  • js在index.html中注册
    【Flutter】Android原生WebView(非Flutter WebView)与FlutterWeb交互_第2张图片
<script src="js/config.js" type="application/javascript">script>
  • flutter调用
class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
      
    //调用js代码
    var result = js.context.callMethod("flutterGetJs",["123"]);
    Fluttertoast.showToast(msg: result);
      
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'default',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: ProviderTestPage01(),
      routes: routeTable,
    );
  }
}
  • 测试结果
    【Flutter】Android原生WebView(非Flutter WebView)与FlutterWeb交互_第3张图片

FlutterWeb打包

命令行进入flutterweb目录下,或者在FlutterWeb项目的Terminal里面输入:

flutter build web

【Flutter】Android原生WebView(非Flutter WebView)与FlutterWeb交互_第4张图片
会在flutter_web/build下生成如下内容:
【Flutter】Android原生WebView(非Flutter WebView)与FlutterWeb交互_第5张图片
将web打包部署到服务端。

将FlutterWeb部署到服务端(本地服务)

tomcat安装可以参考mac安装tomcat

我们将web这个文件夹移动到tomcat/webapps目录下
【Flutter】Android原生WebView(非Flutter WebView)与FlutterWeb交互_第6张图片
需要注意的是,index.html中如果不修改base href,部署后是显示不出来页面的
所以,我们需要打开index.html进行编辑
修改 上述的ip为你自己电脑的ip地址。
【Flutter】Android原生WebView(非Flutter WebView)与FlutterWeb交互_第7张图片
最后,我们就可以使用浏览器进行访问了
在浏览器中输入http://10.99.174.134:8080/web/index.html ,回车,出现了如下页面
【Flutter】Android原生WebView(非Flutter WebView)与FlutterWeb交互_第8张图片

ItVuer - 免责声明 - 关于我们 - 联系我们

本网站信息来源于互联网,如有侵权请联系:561261067@qq.com

桂ICP备16001015号