liyufengrex / flutter_subscreen_plugin

flutter插件:支持 Android 设备双屏显示,主副屏皆使用 flutter 绘制,通过 channel 双引擎实现主副屏通信交互。
BSD 3-Clause "New" or "Revised" License
123 stars 24 forks source link

副屏接收数据转model类型转换问题 #13

Open Steven-Yung opened 1 year ago

Steven-Yung commented 1 year ago

发送端将model转换成Map后发送到副屏,副屏再将接收到的JSON转换成model时,报如下错误,导致类型无法转换 Unhandled Exception: type '_Map<Object?, Object?>' is not a subtype of type 'Map<String, dynamic>' JSON转model,model转JSON用三方库json_serializable

发送端代码:

@JsonSerializable()
class SubScreenMessage {
  int? code;

  dynamic message;

  SubScreenMessage();

  factory SubScreenMessage.fromJson(Map<String, dynamic> json) => _$SubScreenMessageFromJson(json);

  Map<String, dynamic> toJson() => _$SubScreenMessageToJson(this);
}
var mapObj = message.toJson();
print('发送消息到副屏消息 : $mapObj');
SubScreenPlugin.sendMsgToViceScreen('key',  params: mapObj);

副屏代码:

SubScreenPlugin.viceStream.listen((event) {
    // 接收到消息
    var message = SubScreenMessage.fromJson(event.arguments);
    // [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: type '_Map<Object?, Object?>' is not a subtype of type 'Map<String, dynamic>'
}
Steven-Yung commented 1 year ago

传输使用map,用encode、decode、分别处理发送端和接收端,中间层的数据格式保持是字符串格式

意思是转成String格式再传输?sendMsgToViceScreen('key', params: {'硬编码': 传输的数据转string}) 就是感觉每次发送数据都硬编码params就不是很舒服 如果是这样的话,params的类型改为dynamic是不是更好呢?这样就不用再造一个Map<String, dynamic>的params了 这样: sendMsgToViceScreen('key', params: 传输的数据转string)

liyufengrex commented 1 year ago

发送:sendMsgToViceScreen('key', params: Map<String, dynamic>) 接收: final key = event.method; final params = encode(event.arguments);