How to use dart-protobuf

血红的双手。 提交于 2020-01-13 10:26:08

问题


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.


回答1:


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




回答2:


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;
  }


来源:https://stackoverflow.com/questions/21770445/how-to-use-dart-protobuf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!