flutter 跨平台编码库 protobuf 工具使用

1 安装依赖`

dart 复制代码
dependencies:
  protobuf: ^3.1.0  # 或最新版本
dart 复制代码
flutter pub get

安装成功之后

1 lib 下创建文件夹 testProto

2 创建文件Student.proto 文件

Student.proto 文件内容

c 复制代码
syntax = "proto3";
package  example2;

//导入其它proto文件
import "testProto/user.proto";

/*
每个字段都要有唯一的编号(1、2、3...)。
*/
message  Student {
    int32 id = 1;  //用户ID
    string 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
*/

安装工具

c 复制代码
brew install protobuf // 安装生成dart工具
brew install swift-protobuf // 安装生成swift工具

命令行

切换到lib根路径

创建testProto的lib文件夹

c 复制代码
protoc --dart_out=testProto/lib testProto/Student.proto

生成文件如下

在dart中使用

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("反序列化");

    //序列化为JSON
    var stuJson = stu.writeToJson();
    print("序列化为json数据$stuJson");
    var student3 = Student.fromJson(stuJson);
    print("反序列化$student3");

  }

会生成二进制数据,也就是类类型转为二进制数据,和硬件通信很适合,我这边目前主要用于定义协议

相关推荐
奥尔特星云大使2 小时前
MySQL 慢查询日志slow query log
android·数据库·mysql·adb·慢日志·slow query log
SoaringHeart4 小时前
Flutter进阶:自定义一个 json 转 model 工具
前端·flutter·dart
2501_915918416 小时前
iOS 框架全解析,原生框架与跨平台框架对比、开发应用打包与 App Store 上架实战经验
android·ios·小程序·https·uni-app·iphone·webview
K24B;7 小时前
多模态大语言模型LISA++
android·人工智能·语言模型·分割·多模态大语言模型
许泽宇的技术分享9 小时前
Flutter + Ollama:开启本地AI的全平台新纪元 —— 从零剖析一款现代化AI客户端的技术奥秘
人工智能·flutter
molihuan12 小时前
开源 全平台 哔哩哔哩缓存视频合并 Github地址:https://github.com/molihuan/hlbmerge_flutter
android·flutter·缓存·ffmpeg·开源·github·音视频
奶糖 肥晨12 小时前
批量重命名技巧:使用PowerShell一键整理图片文件命名规范
android·服务器·数据库
Momentary_SixthSense13 小时前
如何对较长的Stream链进行Debug
android·java·开发语言
little_fat_sheep14 小时前
【Rive】rive-android源码分析
android
教程分享大师15 小时前
新魔百和m401h全部版本当贝桌面固件卡刷包和线刷包带adb权限
android