何为gRPC
In gRPC, a client application can directly call a method on a server application on a different machine as if it were a local object, making it easier for you to create distributed applications and services. As in many RPC systems, gRPC is based around the idea of defining a service, specifying the methods that can be called remotely with their parameters and return types. On the server side, the server implements this interface and runs a gRPC server to handle client calls. On the client side, the client has a stub (referred to as just a client in some languages) that provides the same methods as the server.
参考资料 https://grpc.io/docs/languages/dart/quickstart/
因为Flutter 项目中用到了grpc,所以只能各种找资料安装,要想在dart中能用grpc必须满足三个先决条件
大概意思就是说1,你的dart版本要大于2.12,安装 Protocol buffer 以及协议编译器
好,了解了这些先决条件以后就可以正式开始gRPC在dart中的使用之旅了。
首先检查下当前所使用的dart版本是否满足上述条件大于2.12及以上,如果小于这个版本的先升级下dart版本。
接下来就是安装 Protocol buffer
1 下载 https://github.com/protocolbuffers/protobuf/tags 选择自己需要安装的版本下载
2 下载完解压 安装
cd protobuf-3.18.0(下载的protobuf文件 我用的3.18.0的版本)
设置编译目录
./configure --prefix=/usr/local/protobuf
(/usr/local/protobuf/ 为自己配置的编译安装目录)
然后执行安装
make
make install
配置环境变量
终端 执行 vim .bash_profile
添加配置文件
export PROTOBUF=/usr/local/protobuf
export PATH=$PROTOBUF/bin:$PATH
export PATH=$PATH:$HOME/.pub-cache/bin
执行source .bash_profile 使配置生效
完成以后就可以查看安装结果了 输入protoc --version
看到如下结果表示安装成功:
protoc --version
libprotoc 3.18.0
注意:当你弄完这些后满心欢喜的准备更新proto时 protoc --dart_out=grpc:lib/src/generated -Iprotos protos/helloworld.proto
报错了 Can't load Kernel binary: Invalid kernel binary format version.
Failed to precompile protoc_plugin:protoc_plugin:
../../.pub-cache/hosted/pub.flutter-io.cn/watcher-1.0.1/lib/watcher.dart:1:1: Error: The specified language version is too high. The highest supported language version is 2.12.
// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file
这是因为缺少了最关键的能在dart中使用的编译器 报错如下
只需要执行一下 dart pub global activate protoc_plugin
待执行完后 还须在配置环境中添加
exportPATH="$PATH:$HOME/.pub-cache/bin"
添加完后,在Dart中使用gRPC就全部弄好了,可以试下更新数据和新增protos文件