Dart Quick Start

This guide gets you started with gRPC in Dart with a simple working example.

Prerequisites

  • Dart SDK version 2.2 or higher. For installation instructions, seeInstallDart.

Note

Dart gRPC supports the Flutter and Server platforms.

Protocol Buffers v3

While not mandatory, gRPC applications usually leverageProtocol Buffersv3 for service definitions and data serialization, and the example codeuses Protocol Buffers.

  • macOS:
  1. $ brew install protobuf
  • Any OS:

    • Download a zip file of the latest version of pre-compiled binaries foryour operating system fromgithub.com/google/protobuf/releases(protoc-<version>-<os>.zip).
    • Unzip the file.
    • Update your environment’s path variable to include the path to theprotoc executable.

Next, install the protoc plugin for Dart

  1. $ pub global activate protoc_plugin

The compiler plugin, protoc-gen-dart, is installed in $HOME/.pub-cache/bin.It must be in your PATH for the protocol compiler, protoc, to find it.

  1. $ export PATH=$PATH:$HOME/.pub-cache/bin

Download the example

You’ll need a local copy of the example code to work through this quick start.Download the example code from our GitHub repository (the following commandclones the entire repository, but you just need the examples for this quick startand other tutorials):

  1. # Clone the repository at the latest release to get the example code:
  2. $ git clone https://github.com/grpc/grpc-dart
  3. # Navigate to the "Hello World" Dart example:
  4. $ cd grpc-dart/example/helloworld

Run a gRPC application

From the example/helloworld directory:

  • Download package dependencies
  1. $ pub get
  • Run the server:
  1. $ dart bin/server.dart
  • From another terminal, run the client:
  1. $ dart bin/client.dart

Congratulations! You’ve just run a client-server application with gRPC.

Update a gRPC service

In this section you’ll update the application with an extra server method.The gRPC service is defined using protocol buffers.To learn more about how to define a service in a .protofile seegRPC Basics: Dart.For now, all you need to know is that both theserver and the client “stub” have a SayHello() RPC method that takes aHelloRequest parameter from the client and returns a HelloReply from theserver, and that this method is defined like this:

  1. // The greeting service definition.
  2. service Greeter {
  3. // Sends a greeting
  4. rpc SayHello (HelloRequest) returns (HelloReply) {}
  5. }
  6. // The request message containing the user's name.
  7. message HelloRequest {
  8. string name = 1;
  9. }
  10. // The response message containing the greetings
  11. message HelloReply {
  12. string message = 1;
  13. }

Edit protos/helloworld.proto and add a new SayHelloAgain() method, with thesame request and response types:

  1. // The greeting service definition.
  2. service Greeter {
  3. // Sends a greeting
  4. rpc SayHello (HelloRequest) returns (HelloReply) {}
  5. // Sends another greeting
  6. rpc SayHelloAgain (HelloRequest) returns (HelloReply) {}
  7. }
  8. // The request message containing the user's name.
  9. message HelloRequest {
  10. string name = 1;
  11. }
  12. // The response message containing the greetings
  13. message HelloReply {
  14. string message = 1;
  15. }

Remember to save the file!

Generate gRPC code

Before you can use the new service method, you need to recompile the updatedproto file.

From the example/helloworld directory, run:

  1. $ protoc --dart_out=grpc:lib/src/generated -Iprotos protos/helloworld.proto

You’ll find the regenerated request and response classes, and client and serverclasses in the lib/src/generated directory.

Update and run the application

You have new generated server and client code, but you still need to implementand call the new method in the human-written parts of our example application.

Update the server

In the same directory, open bin/server.dart. Add the followingsayHelloAgain() method to the GreeterService class:

  1. class GreeterService extends GreeterServiceBase {
  2. @override
  3. Future<HelloReply> sayHello(ServiceCall call, HelloRequest request) async {
  4. return HelloReply()..message = 'Hello, ${request.name}!';
  5. }
  6. @override
  7. Future<HelloReply> sayHelloAgain(ServiceCall call, HelloRequest request) async {
  8. return HelloReply()..message = 'Hello again, ${request.name}!';
  9. }
  10. }

Update the client

Add a call to sayHelloAgain() in bin/client.dart like this:

  1. Future<void> main(List<String> args) async {
  2. final channel = ClientChannel(
  3. 'localhost',
  4. port: 50051,
  5. options: const ChannelOptions(credentials: ChannelCredentials.insecure()),
  6. );
  7. final stub = GreeterClient(channel);
  8. final name = args.isNotEmpty ? args[0] : 'world';
  9. try {
  10. var response = await stub.sayHello(HelloRequest()..name = name);
  11. print('Greeter client received: ${response.message}');
  12. response = await stub.sayHelloAgain(HelloRequest()..name = name);
  13. print('Greeter client received: ${response.message}');
  14. } catch (e) {
  15. print('Caught error: $e');
  16. }
  17. await channel.shutdown();
  18. }

Run!

Run the client and server like you did before. Execute the following commandsfrom the example/helloworld directory:

  • Run the server:
  1. $ dart bin/server.dart
  • From another terminal, run the client. This time, add a name as a command-lineargument:
  1. $ dart bin/client.dart Alice

You’ll see the following output:

  1. Greeter client received: Hello, Alice!
  2. Greeter client received: Hello again, Alice!

What’s next

Reporting issues

If you find a problem with Dart gRPC, pleasefile an issuein our issue tracker.