0
点赞
收藏
分享

微信扫一扫

Flutter与原生(Android/IOS)的消息通信

一、Flutter与Android的消息通信

1、Android端实现接收消息和发送消息

  • Java版
    public class MainActivity extends FlutterActivity {
     @Override
     public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) {
       GeneratedPluginRegistrant.registerWith(flutterEngine);
       MethodChannel  mc = new MethodChannel(flutterEngine.getDartExecutor(), "com.cc.flutter.native"); //此处名称应与Flutter端保持一致
       //接收Flutter消息
       mc.setMethodCallHandler(new MethodChannel.MethodCallHandler() {
               @Override
               public void onMethodCall(@NonNull MethodCall call, @NonNull MethodChannel.Result result) {
                   System.out.println("MethodChannel call.method:"+call.method+ "  call arguments:"+call.arguments);
                   switch (call.method){
                       case "envType":
                           result.success("2");
                           break;
                       case "toast":
                           String msg = call.argument("msg");
                           Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
                           result.success("成功啦");
                           break;
                       default:
                           result.error("404", "未匹配到对应的方法"+call.method, null);
                   }
               }
           });
     
    //     mc.invokeMethod("aaa", "c")  //发送消息
     }
    }
    
  • Kotlin版
    class MainActivity : FlutterActivity(){     
       override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
           var methodChannel = MethodChannel(flutterEngine.dartExecutor, "com.cc.flutter.native")
           methodChannel.setMethodCallHandler { call: MethodCall, result: MethodChannel.Result? ->
               println("MethodChannel call.method:" + call.method + "  call arguments:" + call.arguments)
               when (call.method) {
                   "envType" -> result!!.success("2")
                   "toast" -> {
                       val msg = call.argument<String>("msg")
                       showToast(msg!!)
                       result!!.success("成功啦")
                   }
                   else -> result!!.error("404", "未匹配到对应的方法" + call.method, null)
               }
           }
       }
    }
    

2、Flutter测试实现发送消息和接收消息

class NativeUtils{

  static const String NATIVE_CHANNEL_NAME = "com.cc.flutter.native"; //给native发消息,此处应和客户端名称保持一致
  //channel_name每一个通信通道的唯一标识,在整个项目内唯一!!!
  static const _channel = const MethodChannel(NATIVE_CHANNEL_NAME);

  ///
  /// @Params:
  /// @Desc: 获取native的数据
  ///
  static getNativeData(key,[ dynamic arguments ]) async{
    try {
      String resultValue = await _channel.invokeMethod(key, arguments);
      return resultValue;
    }on PlatformException catch (e){
      print(e.toString());
      return "";
    }
  }
  
   static registerMethod(){
    //接收处理原生消息
    _channel.setMethodCallHandler((handler) {
      switch (handler.method) {
        case "aaa": 
          // 发送原生消息
          _channel.invokeMethod("toast", {"msg": "您调用了dart里的方法"});
          break;
      }
    });
  }
}
  1. 在Flutter页面初始化时调用NativeUtils.registerMethod()后,这样客户端调用methodChannel.invokeMethod("aaa", "c") 此时Flutter才能收到对应的消息。
  2. 在Flutter页面中调用NativeUtils. getNativeData("envType") 此时才能调用原生客户端对应的方法获取数据。

以上是Flutter与Android端相互通信的部分,下面部分是Flutter与IOS相互通信的部分。


二、Flutter与IOS的消息通信

1. Android端实现接收消息和发送消息

  • Object-C版
    #import "AppDelegate.h"
    #include "GeneratedPluginRegistrant.h"
    #import "FlutterNativePlugin.h"
    
    @implementation AppDelegate
    
    - (BOOL)application:(UIApplication *)application
        didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
        [GeneratedPluginRegistrant registerWithRegistry:self];
        FlutterViewController* controller = (FlutterViewController*)self.window.rootViewController;
       
         FlutterMethodChannel* channel = [FlutterMethodChannel methodChannelWithName:@"com.cc.flutter.native" binaryMessenger:controller.binaryMessenger];
       
         [channel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {
             if ([call.method isEqualToString:@"cityId"]) {
                 result([NSNumber numberWithInt:1]);
             } if([call.method isEqualToString:@"envType"]){
                 result(@"1");
             } else {
               result(FlutterMethodNotImplemented);
           }
       }];
    
      return [super application:application didFinishLaunchingWithOptions:launchOptions];
    }
    
    @end
    
  • Swift版
    import UIKit
    import Flutter
    
    @UIApplicationMain
    @objc class AppDelegate: FlutterAppDelegate {
      override func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
      ) -> Bool {
        GeneratedPluginRegistrant.register(with: self)
    
        let controller:FlutterViewController = window.rootViewController as! FlutterViewController
        let channel = FlutterMethodChannel(name: "com.cc.flutter.native", binaryMessenger: controller.binaryMessenger)
        channel.setMethodCallHandler { (call, result) in
            if "cityId" == call.method{
                result(1);
            }
            else if "envType" == call.method{
                result("1");
            }
            else{
                result(FlutterMethodNotImplemented)
            }
        }    
        return super.application(application, didFinishLaunchingWithOptions: launchOptions)
      }
    }
    
    

2. Flutter端测试实现发送消息和接收消息代码和Android共用即可。

举报

相关推荐

0 条评论