日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

【Flutter】Flutter 混合开发 ( Flutter 与 Native 通信 | 完整代码示例 )

發(fā)布時間:2025/6/17 编程问答 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【Flutter】Flutter 混合开发 ( Flutter 与 Native 通信 | 完整代码示例 ) 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

文章目錄

  • 前言
  • 一、Android 端完整代碼示例
  • 二、Flutter 端完整代碼示例
  • 三、相關(guān)資源

前言

前置博客 :

  • 【Flutter】Flutter 混合開發(fā) ( Flutter 與 Native 通信 | 在 Flutter 端實(shí)現(xiàn) BasicMessageChannel 通信 )
  • 【Flutter】Flutter 混合開發(fā) ( Flutter 與 Native 通信 | 在 Flutter 端實(shí)現(xiàn) MethodChannel 通信 )
  • 【Flutter】Flutter 混合開發(fā) ( Flutter 與 Native 通信 | 在 Flutter 端實(shí)現(xiàn) EventChannel 通信 )
  • 【Flutter】Flutter 混合開發(fā) ( Flutter 與 Native 通信 | Android 端實(shí)現(xiàn) BasicMessageChannel 通信 )
  • 【Flutter】Flutter 混合開發(fā) ( Flutter 與 Native 通信 | Android 端實(shí)現(xiàn) EventChannel 通信 )
  • 【Flutter】Flutter 混合開發(fā) ( Flutter 與 Native 通信 | Android 端實(shí)現(xiàn) MethodChannel 通信 )

執(zhí)行效果 : 在 Android 端嵌入 FlutterFragment , 通過 333 種不同的 Channel 進(jìn)行 Android 端 與 Flutter 端進(jìn)行通信 ;





一、Android 端完整代碼示例



package com.example.flutter_native;import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.FragmentTransaction;import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.TextView;import io.flutter.embedding.android.FlutterActivity; import io.flutter.embedding.android.FlutterFragment; import io.flutter.plugin.common.BasicMessageChannel; import io.flutter.plugin.common.EventChannel; import io.flutter.plugin.common.MethodCall; import io.flutter.plugin.common.MethodChannel; import io.flutter.plugin.common.StringCodec;public class MainActivity extends AppCompatActivity {private static final String TAG = "Flutter MainActivity";/*** 嵌入到 Activity 界面的 FlutterFragment*/private FlutterFragment mFlutterFragment;/*** 顯示收發(fā)消息的組件*/private TextView show_message;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);show_message = findViewById(R.id.show_message);findViewById(R.id.flutter1).setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {FragmentTransaction fragmentTransaction =getSupportFragmentManager().beginTransaction();// 使用該方法創(chuàng)建的 Fragment 沒有傳遞數(shù)據(jù)//FlutterFragment.createDefault()// 打開默認(rèn)界面//fragmentTransaction.replace(R.id.frame, FlutterFragment.createDefault());mFlutterFragment = FlutterFragment.withNewEngine().initialRoute("嵌入 FlutterFragment").build();Log.i(TAG, "mFlutterFragment : " + mFlutterFragment);// 創(chuàng)建 FlutterFragmentfragmentTransaction.replace(R.id.frame, mFlutterFragment);fragmentTransaction.commit();//initBasicMessageChannel();new Thread(){@Overridepublic void run() {try {sleep(5000);} catch (InterruptedException e) {e.printStackTrace();}initBasicMessageChannel();initEventChannel();initMethodChannel();Log.i(TAG, "mFlutterFragment : " + mFlutterFragment);}}.start();}});findViewById(R.id.flutter2).setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {Intent intent = FlutterActivity.withNewEngine().initialRoute("啟動 FlutterActivity").build(MainActivity.this);intent.putExtra("initParams", "啟動 FlutterActivity2");startActivity(intent);}});}/*** BasicMessageChannel 消息傳遞通道*/private BasicMessageChannel mBasicMessageChannel;/*** 初始化 BasicMessageChannel*/private void initBasicMessageChannel() {// 初始化mBasicMessageChannel = new BasicMessageChannel(mFlutterFragment.getFlutterEngine().getDartExecutor(),"BasicMessageChannel",StringCodec.INSTANCE);// 設(shè)置消息接收監(jiān)聽mBasicMessageChannel.setMessageHandler(new BasicMessageChannel.MessageHandler<String>() {@Overridepublic void onMessage(@Nullable String message, @NonNull BasicMessageChannel.Reply reply) {show_message.setText("Dart 通過 BasicMessageChannel 通道向 Native 發(fā)送 " + message + " 信息");}});// 點(diǎn)擊按鈕發(fā)送消息 , 并設(shè)置 Reply 接收 Dart 返回的消息findViewById(R.id.channel1).setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {mBasicMessageChannel.send("Native 通過 BasicMessageChannel 通道發(fā)送消息 Hello !",new BasicMessageChannel.Reply() {@Overridepublic void reply(@Nullable Object reply) {show_message.setText("Native 通過 BasicMessageChannel 通道發(fā)送消息 Hello 后 , Dart 反饋的信息 ");}});}});}/*** 與 Flutter 進(jìn)行消息交互的通道*/private EventChannel mEventChannel;private EventChannel.EventSink mEventSink;/*** 初始化 EventChannel*/private void initEventChannel() {// 初始化 EventChannel 實(shí)例對象mEventChannel = new EventChannel(mFlutterFragment.getFlutterEngine().getDartExecutor(),"EventChannel");Log.i(TAG, "mEventChannel 初始化成功 , mEventChannel : " + mEventChannel);mEventChannel.setStreamHandler(new EventChannel.StreamHandler() {/*** 事件流建立成功會回調(diào)該方法* @param arguments* @param events*/@Overridepublic void onListen(Object arguments, EventChannel.EventSink events) {mEventSink = events;Log.i(TAG, "事件流建立成功");}@Overridepublic void onCancel(Object arguments) {mEventSink = null;}});Log.i(TAG, "mEventChannel StreamHandler 設(shè)置完成");findViewById(R.id.channel2).setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {Log.i(TAG, "Native 通過 EventChannel 通道發(fā)送消息 , mEventSink : " + mEventSink);// 點(diǎn)擊按鈕 , 向 Flutter 端發(fā)送數(shù)據(jù)if (mEventSink != null) {mEventSink.success("Native 通過 EventChannel 通道發(fā)送消息 Hello !");}}});}/*** 方法調(diào)用消息通道*/private MethodChannel mMethodChannel;/*** 初始化 MethodChannel*/private void initMethodChannel() {mMethodChannel = new MethodChannel(mFlutterFragment.getFlutterEngine().getDartExecutor(), "MethodChannel");mMethodChannel.setMethodCallHandler(new MethodChannel.MethodCallHandler() {@Overridepublic void onMethodCall(@NonNull MethodCall call, @NonNull MethodChannel.Result result) {show_message.setText("Dart 端通過 MethodChannel 調(diào)用 Android 端的 " + call.method + " 方法 , 參數(shù)是 " + call.arguments);}});findViewById(R.id.channel3).setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {mMethodChannel.invokeMethod("method", "arguments");}});}}



二、Flutter 端完整代碼示例



import 'dart:async';import 'package:flutter/material.dart';// 使用 window.defaultRouteName 必須導(dǎo)入當(dāng)前 UI 庫 import 'dart:ui';import 'package:flutter/services.dart';void main() => runApp(/// 該構(gòu)造方法中傳入從 Android 中傳遞來的參數(shù)MyApp(initParams: window.defaultRouteName,) );class MyApp extends StatelessWidget {/// 這是從 Android 中傳遞來的參數(shù)final String initParams;/// 構(gòu)造方法 , 獲取從 Android 中傳遞來的參數(shù)const MyApp({Key? key, required this.initParams}):super(key: key);@overrideWidget build(BuildContext context) {return MaterialApp(title: 'Flutter Demo',theme: ThemeData(primarySwatch: Colors.blue,),home: MyHomePage(title: "初始參數(shù) : $initParams"),);} }class MyHomePage extends StatefulWidget {MyHomePage({Key? key, required this.title}) : super(key: key);final String title;@override_MyHomePageState createState() => _MyHomePageState(); }class _MyHomePageState extends State<MyHomePage> {/// 展示從 Native 獲取的消息String showMessage = "";static const BasicMessageChannel _basicMessageChannel =const BasicMessageChannel('BasicMessageChannel', StringCodec());static const MethodChannel _methodChannel =const MethodChannel('MethodChannel');static const EventChannel _eventChannel =EventChannel('EventChannel');/// 監(jiān)聽 EventChannel 數(shù)據(jù)的句柄late StreamSubscription _streamSubscription;/// 當(dāng)前使用的消息通道是否是 MethodChannelbool _isMethodChannel = false;@overridevoid initState() {/// 從 BasicMessageChannel 通道獲取消息_basicMessageChannel.setMessageHandler((message) => Future<String>((){setState(() {showMessage = "BasicMessageChannel : $message";});return "BasicMessageChannel : $message";}));/// 這里延遲 6 秒在注冊該事件/// 一定要先在 Android 中設(shè)置好 EventChannel/// 然后 , 才能在 Flutter 中設(shè)置監(jiān)聽/// 否則 , 無法成功Future.delayed(const Duration(milliseconds: 6000), () {// Here you can write your code// 注冊 EventChannel 監(jiān)聽_streamSubscription = _eventChannel.receiveBroadcastStream()/// StreamSubscription<T> listen(void onData(T event)?,/// {Function? onError, void onDone()?, bool? cancelOnError});.listen(/// EventChannel 接收到 Native 信息后 , 回調(diào)的方法(message) {print("Flutter _eventChannel listen 回調(diào)");setState(() {/// 接收到消息 , 顯示在界面中showMessage = message;});},onError: (error){print("Flutter _eventChannel listen 出錯");print(error);});setState(() {});});// Future<dynamic> Function(MethodCall call)? handler_methodChannel.setMethodCallHandler((call) {var method = call.method;var arguments = call.arguments;setState(() {showMessage = "Android 端通過 MethodChannel 調(diào)用 Flutter 端 $method 方法, 參數(shù)為 $arguments";});return Future.value();});/*// 注冊 EventChannel 監(jiān)聽_streamSubscription = _eventChannel.receiveBroadcastStream()/// StreamSubscription<T> listen(void onData(T event)?,/// {Function? onError, void onDone()?, bool? cancelOnError});.listen(/// EventChannel 接收到 Native 信息后 , 回調(diào)的方法(message) {print("Flutter _eventChannel listen 回調(diào)");setState(() {/// 接收到消息 , 顯示在界面中showMessage = message;});},onError: (error){print("Flutter _eventChannel listen 出錯");print(error);});*/print("Flutter _eventChannel 注冊完畢");super.initState();}@overridevoid dispose() {// 取消監(jiān)聽_streamSubscription.cancel();super.dispose();}@overrideWidget build(BuildContext context) {return Scaffold(appBar: AppBar(title: Text(widget.title),),body: Container(alignment: Alignment.topCenter,decoration: BoxDecoration(color: Colors.amber),margin: EdgeInsets.only(top: 0),child: Column(children: [ElevatedButton(onPressed: (){_basicMessageChannel.send("Dart 端通過 BasicMessageChannel 向 Android 端發(fā)送消息 Hello !");},child: Text("BasicMessageChannel 向 Android 發(fā)送消息"),),ElevatedButton(onPressed: (){_methodChannel.invokeMethod("method", "arguments");},child: Text("MethodChannel 調(diào)用 Android 方法"),),Container(color: Colors.black,child: Text("Native 傳輸?shù)南?: $showMessage",style: TextStyle(color: Colors.green),),),],),), // This trailing comma makes auto-formatting nicer for build methods.);} }



三、相關(guān)資源



參考資料 :

  • Flutter 官網(wǎng) : https://flutter.dev/
  • Flutter 插件下載地址 : https://pub.dev/packages
  • Flutter 開發(fā)文檔 : https://flutter.cn/docs ( 強(qiáng)烈推薦 )
  • 官方 GitHub 地址 : https://github.com/flutter
  • Flutter 中文社區(qū) : https://flutter.cn/
  • Flutter 實(shí)用教程 : https://flutter.cn/docs/cookbook
  • Flutter CodeLab : https://codelabs.flutter-io.cn/
  • Dart 中文文檔 : https://dart.cn/
  • Dart 開發(fā)者官網(wǎng) : https://api.dart.dev/
  • Flutter 中文網(wǎng) : https://flutterchina.club/ , http://flutter.axuer.com/docs/
  • Flutter 相關(guān)問題 : https://flutterchina.club/faq/ ( 入門階段推薦看一遍 )
  • GitHub 上的 Flutter 開源示例 : https://download.csdn.net/download/han1202012/15989510
  • Flutter 實(shí)戰(zhàn)電子書 : https://book.flutterchina.club/chapter1/
  • Dart 語言練習(xí)網(wǎng)站 : https://dartpad.dartlang.org/

重要的專題 :

  • Flutter 動畫參考文檔 : https://flutterchina.club/animations/

博客源碼下載 :

  • GitHub 地址 : ( 隨博客進(jìn)度一直更新 , 有可能沒有本博客的源碼 )

    • Flutter Module 工程 : https://github.com/han1202012/flutter_module
    • Android 應(yīng)用 : https://github.com/han1202012/flutter_native
    • 注意 : 上面兩個工程要放在同一個目錄中 , 否則編譯不通過 ;
  • 博客源碼快照 : https://download.csdn.net/download/han1202012/21740142 ( 本篇博客的源碼快照 , 可以找到本博客的源碼 )

總結(jié)

以上是生活随笔為你收集整理的【Flutter】Flutter 混合开发 ( Flutter 与 Native 通信 | 完整代码示例 )的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。