dart中使用protobuf

文章目录

        • 为什么要使用protobuf
        • 配置环境
        • 编写proto描述文件-person.proto
        • 编译生成dart文件
        • 使用

为什么要使用protobuf

protobuf提供了效率、灵活性和易用性之间的平衡,使其成为各种场景(包括微服务、分布式系统和网络通信)中数据序列化和交换的有吸引力的选择

配置环境
  1. 安装protobuf
  2. 配置环境变量
  3. 引入类库
  4. protoc_plugin
  5. protobuf
    protobuf: ^3.1.0
    protoc_plugin: ^21.1.2
编写proto描述文件-person.proto
syntax = "proto3";
import "google/protobuf/timestamp.proto";
message Person {
  string name = 1;
  int32 id = 2;  // Unique ID number for this person.
  string email = 3;

  enum PhoneType {
    PHONE_TYPE_UNSPECIFIED = 0;
    PHONE_TYPE_MOBILE = 1;
    PHONE_TYPE_HOME = 2;
    PHONE_TYPE_WORK = 3;
  }

  message PhoneNumber {
    string number = 1;
    PhoneType type = 2;
  }

  repeated PhoneNumber phones = 4;

  google.protobuf.Timestamp last_updated = 5;
}

// Our address book file is just one of these.
message AddressBook {
  repeated Person people = 1;
}
编译生成dart文件

protoc --dart_out=. google/protobuf/timestamp.proto
protoc --dart_out=. ./*.proto

使用
test('test Proto', () async {
    final m1 = Person.create()..name = "李四"..id=5..email="123444"..phones.add(Person_PhoneNumber(
      number: "123456",
      type: Person_PhoneType.PHONE_TYPE_HOME,
    ))..lastUpdated = Timestamp(seconds: $fixnum.Int64.parseInt((DateTime.now().millisecondsSinceEpoch~/1000).toString()));
    final result = m1.writeToBuffer();
    print(m1.toString());
    print(m1.name);
    final p2 = Person.fromBuffer(result);
    p2.name = "张三";
    final result2 = p2.writeToBuffer();
    print(result2);
    print(p2.name);
  });

你可能感兴趣的:(flutter,flutter)