I'm considering using dart-protobuf instead of JSON in one of my projects. The problem is that the library does not provide any example of how to use it, and the tests don't really help either.
I'm also a bit confused on how the parsing of .proto
files would work.
So I'm looking for a simple example of how to use this library in dart.
Protocol Buffers (Protobuf) is a free and open-source cross-platform data format used to serialize structured data. It is useful in developing programs to communicate with each other over a network or for storing data.
I use it and it's awesome. Below the part that was the hardest for me (de/serialization). Maybe docs are better now.
send request (query
is the protocol buffer object to send)
request.send(query.writeToBuffer());
receive response (pb.MovieMessage
is the protocol buffer object to deserialize the response to)
request.onLoad.listen((ProgressEvent e) {
if ((request.status >= 200 && request.status < 300) ||
request.status == 0 || request.status == 304) {
List<int> buffer = new Uint8List.view(request.response);
var response = new pb.MovieMessage.fromBuffer(buffer);
EDIT
My method to send a PB request to the server
Future<pb.MovieMessage> send(pb.MovieMessage query) {
var completer = new Completer<pb.MovieMessage>();
var uri = Uri.parse("http://localhost:8080/public/data/");
var request = new HttpRequest()
..open("POST", uri.toString(), async: true)
..overrideMimeType("application/x-google-protobuf")
..setRequestHeader("Accept", "application/x-google-protobuf")
..setRequestHeader("Content-Type", "application/x-google-protobuf")
..responseType = "arraybuffer"
..withCredentials = true // seems to be necessary so that cookies are sent
..onError.listen((e) {
completer.completeError(e);
})
..onProgress.listen((e){},
onError:(e) => _logger.severe("Error: " + e.errorMessage));
request.onReadyStateChange.listen((e){},
onError: (e) => _logger.severe("OnReadyStateChange.OnError: " + e.toString())
);
request.onLoad.listen((ProgressEvent e) {
if ((request.status >= 200 && request.status < 300) ||
request.status == 0 || request.status == 304) {
List<int> buffer = new Uint8List.view(request.response);
var response = new pb.MovieMessage.fromBuffer(buffer);
response.errors.forEach((pb.Error e) => _logger.severe("Error: " + e.errorMessage));
completer.complete(response);
} else {
completer.completeError(e);
}
});
request.send(query.writeToBuffer());
return completer.future;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With