You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Objective-C中通过invokeMethod向Flutter传递数据?

问题解答

完全可以通过Objective-C向Flutter传递数据,你遇到的错误是因为Objective-C中FlutterMethodChannel的方法调用语法和Java完全不同,并非该功能不可用。

错误原因分析

  1. Java中用.调用对象方法,但Objective-C中必须使用[对象 方法名:参数1 :参数2]的语法,invokeMethod是实例方法而非属性,不能用.访问
  2. 你构造字典的代码存在参数顺序错误:dictionaryWithObjectsAndKeys的格式是值, 键, 值, 键, nil,原代码写反了键值顺序

正确实现代码

1. 先确保MethodChannel初始化正确

#import <Flutter/Flutter.h>

// 示例:在ViewController中初始化通道(通道名需和Flutter端保持一致)
FlutterMethodChannel *CHANNEL = [FlutterMethodChannel methodChannelWithName:@"your_channel_unique_name" 
                                                         binaryMessenger:self.flutterViewController];

2. 修正数据构造与方法调用

// 正确构造要传递的字典数据
NSDictionary *data = @{
    @"value1": @101,
    @"value2": @202
};

// 用Objective-C语法调用invokeMethod方法
[CHANNEL invokeMethod:@"iosMethodCallTest" arguments:data];

完整OC类示例

#import <Flutter/Flutter.h>

@interface NativeDataSender : NSObject
@property (nonatomic, strong) FlutterMethodChannel *channel;
@end

@implementation NativeDataSender

- (instancetype)initWithBinaryMessenger:(NSObject<FlutterBinaryMessenger> *)messenger {
    self = [super init];
    if (self) {
        // 初始化通道,名称需与Flutter端匹配
        self.channel = [FlutterMethodChannel methodChannelWithName:@"com.example.data_transfer" 
                                                     binaryMessenger:messenger];
    }
    return self;
}

// 封装向Flutter传递数据的方法
- (void)sendTransDataToFlutter:(NSInteger)val1 secondVal:(NSInteger)val2 {
    NSDictionary *data = @{
        @"Trans1": @(val1),
        @"Trans2": @(val2)
    };
    [self.channel invokeMethod:@"GetTransData" arguments:data];
}

@end

Flutter端接收数据示例

final MethodChannel _channel = MethodChannel('com.example.data_transfer');

@override
void initState() {
  super.initState();
  // 监听原生传来的方法调用
  _channel.setMethodCallHandler((call) async {
    if (call.method == @"GetTransData") {
      int trans1 = call.arguments['Trans1'];
      int trans2 = call.arguments['Trans2'];
      // 处理接收到的数据
      print('Received from iOS: Trans1=$trans1, Trans2=$trans2');
    }
  });
}

内容的提问来源于stack exchange,提问作者Jungwon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 10:52:21