[英]How to send data from Android to Flutter properly?
我正在尝试将数据从 Flutter 来回发送到我的本机平台(在本例中为 Android)。 为了保持模型的一致性,我使用 Protocol-Buffers 为所有平台生成了模型。
当我尝试将数据从 Android 传递到 Flutter 时,我没有找到任何方法来做到这一点,而不需要像序列化到手工制作的 JSON 这样的恶作剧。
必须有一种使用 protobuf 的方法才能这样做,不是吗?
为了提供上下文,我制作了一个最小的应用程序来尝试解决这个问题:
我的协议缓冲区
syntax = "proto3";
option java_package = "com.test.protobuf_test";
option java_outer_classname = "ProtoModel";
message SimplePerson {
int32 id= 1;
string name= 2;
}
我使用以下方法生成我的模型:protoc --java_out 和 protoc --dart_out
在达特我上课
class SimplePerson extends $pb.GeneratedMessage {...}
而在爪哇
public final class ProtoModel {
...
public static final class SimplePerson extends
com.google.protobuf.GeneratedMessageV3 implements
SimplePersonOrBuilder {...}
}
从我的方法通道中的 Android,我试图将一个或多个 ProtoModel.SimplePerson 对象传递回 Dart。
到目前为止没有成功。
你实际上会怎么做? 我希望它类似于在 Java 中:
ProtoModel.SimplePerson person = ProtoModel.SimplePerson.newBuilder().setId(3).setName("Person Name").build();
result(person);
在飞镖中:
var result = await platform.invokeMethod("generatePerson");
if(result is SimplePerson) {
print("Success!");
} else {
print("Failure!");
}
到目前为止,我只收到失败或异常。
谢谢!
你非常接近你的使用结果,但我让它与 result.success 一起工作
when (call.method) {
"getPlatformVersion" -> result.success(getPlatformVersion().toByteArray())
}
private fun getPlatformVersion(): Models.Version {
return Models.Version.newBuilder().setVersionName("Android ${android.os.Build.VERSION.RELEASE}").build()
}
很好的例子在这里https://www.freecodecamp.org/news/flutter-platform-channels-with-protobuf-e895e533dfb7/
编辑没看到这篇文章有多旧我必须使用它因为 Pigeon 仍然是抢先体验,虽然 pigeon 通常更难设置但我更喜欢它
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.