flutter grpc


https://grpc.io/docs/languages/dart/quickstart/

 

1.安裝brew

https://brew.sh/index_zh-cn.html  

ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

前提是機器上安裝了ruby

貌似還需要xcode命令行?

命令行下載

https://developer.apple.com/download/more/

安裝brew可能還報Failed to connect to raw.githubusercontent.com port 443: Connection refused error。這是DNS問題

修改hosts文件

sudo vim /etc/hosts

添加

199.232.28.133 raw.githubusercontent.com

之后再

驗證是否安裝成功

brew --version

按brew花了不少時間

 

2.安裝protobuf

brew install protobuf

 

3.安裝插件

pub global activate protoc_plugin

 

4.添加環境變量

 

vim .bash_profile 

添加

exprot PATH=$PATH:/Users/xx/.pub-cache/bin

 

5.安裝插件

 

 

6.編譯

復制文件到flutter /lib/proto下,proto文件夾隨便起的

 內容

syntax = "proto3";

option csharp_namespace = "MesGrpcServer";

package greet;

// The greeting service definition.
service Greeter {
  // Sends a greeting
  rpc SayHello (HelloRequest) returns (HelloReply);
}

// The request message containing the user's name.
message HelloRequest {
  string name = 1;
}

// The response message containing the greetings.
message HelloReply {
  string message = 1;
}

命令行編譯

protoc --dart_out=grpc:. greet.proto --plugin ~/.pub-cache/bin/protoc-gen-dart

生成

 

7.pubspec.yaml中添加

  protobuf: 1.0.1
  grpc: 2.2.0

 

8.寫flutter客戶端程序

 

import 'package:flutter/material.dart';
import 'package:fluttertest/proto/greet.pbgrpc.dart';
import 'package:grpc/grpc.dart';

class GrpcTest extends StatefulWidget {
  @override
  _GrpcTestState createState() => _GrpcTestState();
}

class _GrpcTestState extends State<GrpcTest> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Center(
        child: MaterialButton(
          child: Text("發送"),
          onPressed: (){
            //創建一個通道
            final channel = ClientChannel(
              '192.168.1.102',
              port: 5000,
              options: const ChannelOptions(credentials: ChannelCredentials.insecure()),
            );

            final stub = GreeterClient(channel);

            ()async{
              HelloRequest http=HelloRequest();
              http.name='tom';
              try{
             var response=  await stub.sayHello(http);
             print(response.message);

              } catch(e){
                print(e);
              }
              await channel.shutdown();
            }();
          },
        ),
      ),
    );
  }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM