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

无法从Dart向Swift传递数据:参数'data'缺失或无效问题排查

Flutter与Swift端参数传递失败排查方案

问题现象

调用加密接口时持续报错:

flutter: PlatformException(INVALID_ARGUMENT, Parameter 'data' is missing or invalid, null, null)

核心原因

Dart端直接传递的List<int>会被序列化为普通Int数组,而Swift端代码错误地尝试将其解析为FlutterStandardTypedData类型,导致参数匹配失败。

解决办法

方案1:Dart端手动封装为FlutterStandardTypedData

修改Dart调用原生的代码,将List<int>转为Uint8List后封装成FlutterStandardTypedData,适配Swift端的解析逻辑:

import 'package:flutter/services.dart';

@override
Future<List<int>?> encrypt(List<int> data, List<int> key) async {
  // 转换List<int>为Uint8List并封装
  final typedData = FlutterStandardTypedData.uint8List(Uint8List.fromList(data));
  final typedKey = FlutterStandardTypedData.uint8List(Uint8List.fromList(key));
  
  final result = await methodChannel.invokeMethod<List<int>>('encrypt', { 
    'data': typedData, 
    'key': typedKey 
  });
  return result;
}

此方案下Swift端代码无需修改,可直接解析到正确的Data类型。

方案2:Swift端直接解析普通Int数组

如果不想修改Dart代码,调整Swift端的参数解析逻辑,直接将Int数组转为Data:

private func encrypt(args: [String: Any], result: @escaping FlutterResult) throws {
    do {
        // 从Int数组解析data
        guard let dataIntList = args["data"] as? [Int], 
              let data = Data(bytes: dataIntList, count: dataIntList.count) else {
            result(parameterError(name: "data"))
            return
        }
        
        // 从Int数组解析key
        guard let keyIntList = args["key"] as? [Int], 
              let key = Data(bytes: keyIntList, count: keyIntList.count) else {
            result(parameterError(name: "key"))
            return
        }

        let sealed = try self.encryptData(plainData: data, key: key)
        // 将加密结果转为List<int>返回给Dart
        result(Array(sealed))
    } catch CryptoError.runtimeError(let errorMessage) {
        result(FlutterError(code: "InvalidArgumentError", message: errorMessage.localizedLowercase, details: nil))
    } catch {
        result(FlutterError(code: "EncryptionError", message:"Failed to encrypt: " + error.localizedDescription, details: nil))
    }
}

注意:需确保Dart传递的List<int>元素值在0-255的Uint8范围内,避免转Data时出现数据异常。

额外检查点

  • 确认Dart与Swift端的methodChannel名称完全一致,无拼写错误
  • 在Dart端打印key的类型和内容,验证FlutterKeyGenerator生成的密钥确实为非空List<int>

内容的提问来源于stack exchange,提问作者Kim Mỹ

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 15:37:42