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

如何使用Swift通过Platform Channel修改并回传数据

Platform Channel 个人资料更新日期回传实现方案

现有代码待修正点

  • Flutter端调用invokeMethod时未携带原始个人资料Map参数,iOS端无法获取传入的资料数据
  • Flutter端收到返回后硬编码重置了name、出生日期字段,会覆盖原始传入的资料内容
  • iOS端方法回调为空实现,未做方法名匹配、更新日期生成、结果回传逻辑
  • iOS端原代码未获取FlutterViewController实例直接调用controller属性会触发编译错误

分步实现

1. 修正Flutter端代码

调整方法调用时的参数传递逻辑,保留原始资料字段,仅更新回传的更新日期字段,按钮直接绑定触发方法即可:

static const MethodChannel _platform = MethodChannel('samples.flutter.dev/profile');

Future<PlatformChannelState> _getUpdateProfile(ChangeProfile event) async {
  Map<String, String> newProfile = Map.from(event.newProfile);
  try {
    // 调用平台方法时传入原始profile数据
    final String updateDate = await _platform.invokeMethod(
      'updateProfile',
      {"rawProfile": newProfile}
    );
    // 仅更新更新日期字段,保留原始姓名、生日内容
    newProfile['profile update date'] = updateDate;
  } on PlatformException catch (e) {
    newProfile['profile update date'] = '更新失败: ${e.message}';
  }
  return GotProfileUpdate(newProfile);
}

// ElevatedButton绑定触发逻辑
ElevatedButton(
  onPressed: () {
    // 替换为自身业务的状态管理触发逻辑,传入当前最新的profile数据即可
    context.read<ProfileBloc>().add(ChangeProfile(currentProfileData));
  },
  child: const Text("更新个人资料")
)

2. 补全iOS端逻辑

在方法回调中匹配调用方法,生成格式化的当前时间作为更新日期,通过result回传,同时补全controller实例获取逻辑:

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    // 先获取根FlutterViewController实例
    guard let flutterController = window?.rootViewController as? FlutterViewController else {
      GeneratedPluginRegistrant.register(with: self)
      return super.application(application, didFinishLaunchingWithOptions: launchOptions)
    }

    let profileChannel = FlutterMethodChannel(
      name: "samples.flutter.dev/profile",
      binaryMessenger: flutterController.binaryMessenger
    )
    profileChannel.setMethodCallHandler({ call, result in
      // 过滤不匹配的方法
      guard call.method == "updateProfile" else {
        result(FlutterMethodNotImplemented)
        return
      }
      // 如需读取Flutter传入的原始资料,可解包call.arguments获取
      // let rawProfile = call.arguments as? [String: String] ?? [:]

      // 生成格式化的当前时间作为更新日期,格式可按需调整
      let dateFormatter = DateFormatter()
      dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
      let updateTimeStr = dateFormatter.string(from: Date())

      // 回传结果给Flutter端
      result(updateTimeStr)
    })

    GeneratedPluginRegistrant.register(with: self)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
}

补充说明

  • 如果需要iOS端直接返回修改完成的完整Profile Map而非单独的日期字符串,只需将result()的入参替换为修改后的完整字典,Flutter端对应修改接收类型为Map<String, String>即可
  • 两端传递的参数类型需保持一致,避免出现类型转换异常
  • 日期格式可根据业务需求自定义调整

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 15:27:17