Protobuf(Protocol Buffers)是一种轻量级的数据交换格式,由 Google 开发。它类似于 XML 和 JSON,但是更加高效、紧凑和快速。Protobuf 可以用于序列化结构化数据,例如结构体、消息和配置文件等,以便在不同的系统之间进行通信或存储。
1、搭建flutter开发环境
搭建开发环境就不多说了,网上资料很多,配置好环境变量后flutter命令和dart命令能用就行。
2、安装protobuf
brew install protobuf
3、安装proto_plugin
dart pub global activate protoc_plugin
完成之后输出如下
XUDONGYANG-MB0:pbfile a123$ dart;pub global activate protoc_plugin
Package protoc_plugin is currently active at version;20.0.1.
Resolving dependencies... (4.0s)
The package protoc_plugin is already activated at newest available version.
To recompile executables, first run;`dart pub global deactivate protoc_plugin`.
Installed executable protoc-gen-dart.
Warning: Pub installs executables into;$HOME/.pub-cache/bin, which is not on your path.
You can fix that by adding this to your shell's config file (.bashrc, .bash_profile, etc.):
export PATH="$PATH":"$HOME/.pub-cache/bin"
Activated protoc_plugin 20.0.1.
根据提示,我们添加上环境变量,我这里是在~/.bash_profile添加
export PATH=“$ PATH”:“$HOME/.pub-cache/bin”
4、根据pb文件生成dart文件
我这里在当前目录下创建了一个pbtraining.proto,使用命令
protoc --dart_out=…/lib/protoc --proto_path=pbtraining.proto
–dart_out 是生成文件目录,–proto_path是源文件目录,生成的是.dart文件,如果要生成java文件,用
protoc --javamqq_out=…/lib/protoc --proto_path=pbtraining.proto
5、添加protobuf依赖
打开生成文件,发现它报错,这是因为还没有添加protobuf依赖,在pubspec.yaml中添加
dependencies:
protobuf: ^2.1.0
再打开dart文件就不报错了。
6、代码中使用
java通过生成的类提供的静态方法fromBuffer(data)就可以将二进制数据转化为具体的对象了,dart可以直接使用生成的类。