Question

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.

Was it helpful?

Solution 2

I'm not too familiar with dart-protobuf, but it looks like you have to use the protobuf compiler and the dart-protoc-plugin project to generate your Dart protobuf library from a proto definition.

There are some instructions here: https://github.com/dart-lang/dart-protoc-plugin

OTHER TIPS

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;
  }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top