1 安裝依賴`
dependencies:protobuf: ^3.1.0 # 或最新版本
flutter pub get
安裝成功之后
1 lib 下創建文件夾 testProto
2 創建文件Student.proto 文件
Student.proto 文件內容
syntax = "proto3";
package example2;//導入其它proto文件
import "testProto/user.proto";/*
每個字段都要有唯一的編號(1、2、3…)。
*/
message Student {int32 id = 1; //用戶IDstring name = 3; // 用戶名string email = 2; // 郵箱
}/*
proto3 枚舉必須有一個 0 值,通常作為默認值。
枚舉是強類型的,在 Dart/Swift 里會生成對應的 enum 類型。
*/
enum PhoneType {PHONE_TYPE_UNSPECIFIED = 0 ;MOBILE = 1;HOME = 2;WORK = 3;
}/*
proto3 默認所有字段都是 可選 的(會有默認值)。? string 默認是 ""? number 默認是 0? bool 默認是 false
*/
/*
每個字段都要有唯一的編號(1、2、3…)。
*/
message Test1 {double tempture = 1;float height = 2;int32 age = 3;int64 numId = 4;uint32 idCardNum = 5;uint64 id = 6;bool femal = 7;string name = 8; //utf8 字符串bytes data = 9; //原始字節序列PhoneType type = 10;Student stu11 = 11; // 可以嵌套類型repeated string nameList = 12; // 數組,dart List<String>map<string ,Student> contacts = 13; //Map 鍵值對optional string nickname = 14; //如果你要區分“沒有賦值”與“賦值為默認值”,可以用 optional:User user = 15; // 導入其它proto文件
}
/*
protoc --dart_out=testProto/lib testProto/Student.proto
*/
安裝工具
brew install protobuf // 安裝生成dart工具
brew install swift-protobuf // 安裝生成swift工具
命令行
切換到lib根路徑
創建testProto的lib文件夾
protoc --dart_out=testProto/lib testProto/Student.proto
生成文件如下
在dart中使用
void test1() {var stu = Student()..id = 23..name = "bob"..email = "bob@gmai.com";// 序列化為二進制數據Uint8List dataList = stu.writeToBuffer();print("二進制數據處理");var stu2 = Student.fromBuffer(dataList);print("反序列化");//序列化為JSONvar stuJson = stu.writeToJson();print("序列化為json數據$stuJson");var student3 = Student.fromJson(stuJson);print("反序列化$student3");}
會生成二進制數據,也就是類類型轉為二進制數據,和硬件通信很適合,我這邊目前主要用于定義協議