[英]How to send data from Android to Flutter properly?
I'm trying to send data back and forth from Flutter to my native platform (in this case Android).我正在尝试将数据从 Flutter 来回发送到我的本机平台(在本例中为 Android)。 In order to keep some model consistency, I have generated the models for all platforms by using Protocol-Buffers.
为了保持模型的一致性,我使用 Protocol-Buffers 为所有平台生成了模型。
When I try to pass data from Android to Flutter I'm not finding any way to do it without shenanigans like serializing to a handcrafted JSON.当我尝试将数据从 Android 传递到 Flutter 时,我没有找到任何方法来做到这一点,而不需要像序列化到手工制作的 JSON 这样的恶作剧。
There must be a way to use protobuf in order to do so, isn't it?必须有一种使用 protobuf 的方法才能这样做,不是吗?
In order to give context, I have made a minimal app to try to solve this problem:为了提供上下文,我制作了一个最小的应用程序来尝试解决这个问题:
My Protocol Buffer我的协议缓冲区
syntax = "proto3";
option java_package = "com.test.protobuf_test";
option java_outer_classname = "ProtoModel";
message SimplePerson {
int32 id= 1;
string name= 2;
}
From which I generate my model using: protoc --java_out and protoc --dart_out我使用以下方法生成我的模型:protoc --java_out 和 protoc --dart_out
In Dart I get my class在达特我上课
class SimplePerson extends $pb.GeneratedMessage {...}
And in Java而在爪哇
public final class ProtoModel {
...
public static final class SimplePerson extends
com.google.protobuf.GeneratedMessageV3 implements
SimplePersonOrBuilder {...}
}
From Android inside my method channel, I am trying to pass one or many ProtoModel.SimplePerson objects back to Dart.从我的方法通道中的 Android,我试图将一个或多个 ProtoModel.SimplePerson 对象传递回 Dart。
No success so far.到目前为止没有成功。
How would you actually do it?你实际上会怎么做? I'd expect it to be something like In Java:
我希望它类似于在 Java 中:
ProtoModel.SimplePerson person = ProtoModel.SimplePerson.newBuilder().setId(3).setName("Person Name").build();
result(person);
And in Dart:在飞镖中:
var result = await platform.invokeMethod("generatePerson");
if(result is SimplePerson) {
print("Success!");
} else {
print("Failure!");
}
So far I'm only getting Failures or Exceptions.到目前为止,我只收到失败或异常。
Thanks!谢谢!
your very close your using result but i have it working with result.success你非常接近你的使用结果,但我让它与 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()
}
great example here https://www.freecodecamp.org/news/flutter-platform-channels-with-protobuf-e895e533dfb7/很好的例子在这里https://www.freecodecamp.org/news/flutter-platform-channels-with-protobuf-e895e533dfb7/
EDIT didnt see how old this post was I have to use this as Pigeon is sill early access, and although pigeon was generally harder to set up i do prefer it编辑没看到这篇文章有多旧我必须使用它因为 Pigeon 仍然是抢先体验,虽然 pigeon 通常更难设置但我更喜欢它
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.