Protocol Buffers
suggest changeProtocol Buffers (protobuf) is Google's language-neutral format for serializing structured data. You describe your messages once in a .proto file, and a compiler generates classes for Dart, Go, Java, Python and many other languages. Those classes read and write a compact binary format that every implementation understands.
Compared to JSON, protobuf:
- produces much smaller messages and is faster to parse
- gives you typed, generated classes instead of
Map<String, dynamic> - has well-defined rules for evolving a schema without breaking old clients
- is the message format used by gRPC
The trade-off is that the binary format isn't human-readable, and you need a code generation step.
Setup
You need three things:
-
protoc, the protobuf compiler. Download a release from https://github.com/protocolbuffers/protobuf/releases (extract it and putbinon yourPATH), or install it with a package manager:brew install protobuf,apt install protobuf-compiler,winget install protobuf. -
The Dart plugin for
protoc, which is a Dart package:dart pub global activate protoc_pluginThis installs
protoc-gen-dartinto~/.pub-cache/bin(%LOCALAPPDATA%\Pub\Cache\binon Windows). That directory must be on yourPATH, becauseprotocfinds plugins by name. -
The runtime library in your
pubspec.yaml. Generated code depends onprotobuf, and 64-bit integers useInt64fromfixnum:dependencies: protobuf: ^6.0.0 fixnum: ^1.1.1
Use a protoc_plugin version that matches your protobuf version. The latest plugin generates code for the latest runtime.
Defining messages
Put .proto files in a separate directory, for example protos/addressbook.proto:
syntax = "proto3";
package addressbook;
import "google/protobuf/timestamp.proto";
enum PhoneType {
PHONE_TYPE_UNSPECIFIED = 0;
PHONE_TYPE_MOBILE = 1;
PHONE_TYPE_HOME = 2;
PHONE_TYPE_WORK = 3;
}
message PhoneNumber {
string number = 1;
PhoneType type = 2;
}
message Person {
string name = 1;
int32 id = 2;
string email = 3;
repeated PhoneNumber phones = 4;
map<string, string> labels = 5;
optional int32 age = 6;
int64 balance_cents = 7;
google.protobuf.Timestamp created_at = 8;
oneof contact {
string twitter = 9;
string website = 10;
}
}
message AddressBook {
repeated Person people = 1;
}
The number after each field is its tag. Tags, not names, are what go over the wire, so once a message is in use you must never change a field's tag or type.
Generating Dart code
Run protoc with --dart_out pointing at a directory inside lib:
mkdir -p lib/src/generated
protoc --dart_out=lib/src/generated -Iprotos protos/addressbook.proto
-I sets the directory that imports are resolved from. timestamp.proto is one of the well-known types that ship with protoc. Their Dart classes are part of the protobuf package (package:protobuf/well_known_types/google/protobuf/timestamp.pb.dart), and generated code imports them from there. The output looks like this:
lib/src/generated/
addressbook.pb.dart message classes
addressbook.pbenum.dart enums (exported by addressbook.pb.dart)
addressbook.pbjson.dart descriptors as JSON-like constants
You only import the .pb.dart file. Commit the generated files or regenerate them in your build script, but never edit them by hand.
The Dart names follow Dart conventions: balance_cents becomes balanceCents, and enum values keep their proto names (PhoneType.PHONE_TYPE_MOBILE).
Creating messages
Every message class has a constructor with an optional named parameter per field. You can also start empty and use cascades:
import 'package:fixnum/fixnum.dart';
import 'package:pbdemo/src/generated/addressbook.pb.dart';
void main() {
final alice = Person(
name: 'Alice',
id: 42,
email: 'alice@example.com',
phones: [
PhoneNumber(number: '555-1234', type: PhoneType.PHONE_TYPE_MOBILE),
],
);
final bob = Person()
..name = 'Bob'
..id = 7
..balanceCents = Int64(1234567890123)
..phones.add(PhoneNumber()..number = '555-0000')
..labels['team'] = 'core';
print(alice.name); // Alice
print(bob.phones.length); // 1
print(bob.labels); // {team: core}
print(bob.balanceCents.toInt()); // 1234567890123
}
The Dart types for proto field types:
| Proto type | Dart type |
|---|---|
string |
String |
bytes |
List<int> |
bool |
bool |
int32, uint32, sint32, fixed32 |
int |
int64, uint64, sint64, fixed64 |
Int64 (from fixnum) |
float, double |
double |
repeated T |
List<T> (a PbList) |
map<K, V> |
Map<K, V> (a PbMap) |
| enum | generated class extending ProtobufEnum |
| message | generated class extending GeneratedMessage |
int64 maps to Int64 rather than int because Dart compiled to JavaScript can't represent all 64-bit integers exactly.
Repeated and map fields have no setter. You modify the list or map returned by the getter, or pass an Iterable to the constructor.
Default values and field presence
Reading a field that was never set doesn't throw and doesn't return null. It returns the type's default: '', 0, false, the first enum value, an empty list, or a default instance of a message. Use hasX() to tell whether a field was set and clearX() to unset it:
final p = Person(name: 'Carol');
print(p.hasName()); // true
print(p.email.isEmpty); // true
print(p.hasEmail()); // false
p.clearName();
print(p.hasName()); // false
print(p.name == ''); // true
Fields marked optional in proto3 (like age) have explicit presence: hasAge() remains true after age = 0, and the zero is sent over the wire. Use optional when "not set" and "zero" must mean different things.
Message fields work the same way, which leads to a common surprise. The getter of an unset message field returns a shared, frozen default instance, so you can't modify it in place:
final p = Person();
print(p.hasCreatedAt()); // false
print(p.createdAt.seconds); // 0, reading is fine
// p.createdAt.seconds = Int64(1); // throws UnsupportedError
p.ensureCreatedAt().seconds = Int64(1); // creates and stores the sub-message
print(p.hasCreatedAt()); // true
ensureX() sets the field to a new empty message if it's unset and returns it. Alternatively, assign a whole message: p.createdAt = Timestamp(...).
Enums
Generated enums are classes with a constant per value. Each value has a value (the number) and a name:
final t = PhoneType.PHONE_TYPE_HOME;
print(t.value); // 2
print(t.name); // PHONE_TYPE_HOME
print(PhoneType.valueOf(3)); // PHONE_TYPE_WORK
print(PhoneType.valueOf(99)); // null, unknown number
print(PhoneType.values.length); // 4
Always make the zero value mean "unspecified", as in the example. Zero is the default, so you can't otherwise distinguish "the sender chose this" from "the sender didn't set anything".
Oneof
Fields in a oneof share storage: setting one clears the others. The generated whichX() method tells you which one is set:
String describe(Person p) {
switch (p.whichContact()) {
case Person_Contact.twitter:
return 'twitter: @${p.twitter}';
case Person_Contact.website:
return 'web: ${p.website}';
case Person_Contact.notSet:
return 'no contact';
}
}
void main() {
final p = Person(name: 'Dan');
print(describe(p)); // no contact
p.twitter = 'dan';
print(describe(p)); // twitter: @dan
p.website = 'https://dan.dev';
print(describe(p)); // web: https://dan.dev
print(p.hasTwitter()); // false, setting website cleared it
p.clearContact();
print(describe(p)); // no contact
}
The enum is named after the message and the oneof (Person_Contact), and Dart's exhaustiveness checking makes sure you handle every case.
Serializing to binary
writeToBuffer() returns the encoded bytes as a Uint8List, and the generated fromBuffer() constructor parses them:
import 'package:pbdemo/src/generated/addressbook.pb.dart';
String toHex(List<int> bytes) =>
bytes.map((b) => b.toRadixString(16).padLeft(2, '0')).join();
void main() {
final alice = Person(
name: 'Alice',
id: 42,
email: 'alice@example.com',
phones: [
PhoneNumber(number: '555-1234', type: PhoneType.PHONE_TYPE_MOBILE),
],
);
final bytes = alice.writeToBuffer();
print('${bytes.length} bytes');
print(toHex(bytes));
final decoded = Person.fromBuffer(bytes);
print(decoded.name); // Alice
print(decoded.phones.first.type); // PHONE_TYPE_MOBILE
print(decoded == alice); // true
}
Output:
42 bytes
0a05416c696365102a1a11616c696365406578616d706c652e636f6d220c0a083535352d313233341001
Alice
PHONE_TYPE_MOBILE
true
The same data as JSON with field names takes 112 bytes. Reading the hex: 0a is "field 1, length-delimited", 05 is the length, then Alice in UTF-8; 10 2a is "field 2, varint" with value 42. Unset fields take no space at all.
Generated messages implement == and hashCode by comparing all fields, so you can use them in sets, as map keys and in test assertions.
toString() prints a readable text dump that's handy for debugging:
name: Alice
id: 42
email: alice@example.com
phones: {
number: 555-1234
type: PHONE_TYPE_MOBILE
}
Don't parse this output or rely on its format.
Writing and reading files
Binary messages go straight into files:
import 'dart:io';
import 'package:pbdemo/src/generated/addressbook.pb.dart';
Future<void> main() async {
final book = AddressBook(people: [
Person(name: 'Alice', id: 1),
Person(name: 'Bob', id: 2),
]);
await File('book.bin').writeAsBytes(book.writeToBuffer());
final loaded = AddressBook.fromBuffer(await File('book.bin').readAsBytes());
for (final p in loaded.people) {
print('${p.id}: ${p.name}');
}
}
Output:
1: Alice
2: Bob
Merging
mergeFromBuffer() parses bytes into an existing message instead of a new one. Scalar fields from the new data overwrite old values, repeated fields are appended, and sub-messages are merged recursively. A consequence of the format is that concatenating two encoded messages and parsing the result is the same as merging them:
final a = Person(name: 'Alice', phones: [PhoneNumber(number: '111')]);
final b = Person(name: 'Alicia', id: 42, phones: [PhoneNumber(number: '222')]);
final merged = Person.fromBuffer([...a.writeToBuffer(), ...b.writeToBuffer()]);
print(merged.name); // Alicia
print(merged.id); // 42
print(merged.phones.map((p) => p.number).toList()); // [111, 222]
final m = Person(name: 'Alice')..mergeFromMessage(b);
print(m.name); // Alicia
Streams of messages
The binary format doesn't record where a message ends, so to put several messages in one file or socket you write the length before each one. The standard convention (used by Java's writeDelimitedTo and C++'s SerializeDelimitedToOstream) is a varint length prefix:
import 'dart:typed_data';
import 'package:pbdemo/src/generated/addressbook.pb.dart';
void writeVarint(BytesBuilder out, int value) {
while (value >= 0x80) {
out.addByte((value & 0x7f) | 0x80);
value >>= 7;
}
out.addByte(value);
}
Uint8List writeDelimited(Iterable<Person> people) {
final out = BytesBuilder(copy: false);
for (final p in people) {
final bytes = p.writeToBuffer();
writeVarint(out, bytes.length);
out.add(bytes);
}
return out.takeBytes();
}
Iterable<Person> readDelimited(Uint8List data) sync* {
var pos = 0;
while (pos < data.length) {
var length = 0, shift = 0;
int b;
do {
b = data[pos++];
length |= (b & 0x7f) << shift;
shift += 7;
} while (b & 0x80 != 0);
yield Person.fromBuffer(Uint8List.sublistView(data, pos, pos + length));
pos += length;
}
}
void main() {
final data = writeDelimited([
Person(name: 'Alice', id: 1),
Person(name: 'Bob', id: 2),
Person(name: 'Carol', id: 3),
]);
print('${data.length} bytes');
for (final p in readDelimited(data)) {
print(p.name);
}
}
Output:
28 bytes
Alice
Bob
Carol
JSON
Protobuf defines a canonical JSON mapping, called proto3 JSON. Use it to talk to REST APIs, to log messages, or to interoperate with other languages' JSON output. toProto3Json() returns a JSON-compatible object that you pass to jsonEncode, and mergeFromProto3Json() reads one back:
import 'dart:convert';
import 'package:fixnum/fixnum.dart';
import 'package:pbdemo/src/generated/addressbook.pb.dart';
import 'package:protobuf/well_known_types/google/protobuf/timestamp.pb.dart';
void main() {
final bob = Person()
..name = 'Bob'
..id = 7
..phones.add(PhoneNumber(
number: '555-0000', type: PhoneType.PHONE_TYPE_WORK))
..labels['team'] = 'core'
..age = 0
..balanceCents = Int64(1234567890123)
..createdAt = Timestamp.fromDateTime(DateTime.utc(2026, 1, 15, 10, 30))
..website = 'https://bob.dev';
final json = jsonEncode(bob.toProto3Json());
print(const JsonEncoder.withIndent(' ').convert(jsonDecode(json)));
final parsed = Person()..mergeFromProto3Json(jsonDecode(json));
print(parsed == bob); // true
print(parsed.createdAt.toDateTime()); // 2026-01-15 10:30:00.000Z
}
Output:
{
"name": "Bob",
"id": 7,
"phones": [
{
"number": "555-0000",
"type": "PHONE_TYPE_WORK"
}
],
"labels": {
"team": "core"
},
"age": 0,
"balanceCents": "1234567890123",
"createdAt": "2026-01-15T10:30:00Z",
"website": "https://bob.dev"
}
true
2026-01-15 10:30:00.000Z
Points to note about the mapping:
- Field names are converted to lowerCamelCase. When parsing, both
balanceCentsandbalance_centsare accepted. - Enums are written as their names. Numbers are also accepted when parsing.
- 64-bit integers are written as strings, because JavaScript numbers lose precision above 2^53.
bytesfields are Base64 strings.- Fields with default values are omitted, unless they have explicit presence (
ageabove). - Well-known types have special forms: a
Timestampis an RFC 3339 string, aDurationis a string like"1.5s".
By default, an unknown field name in the input throws a FormatException. When reading JSON from a newer version of a service, pass ignoreUnknownFields: true:
final p = Person()
..mergeFromProto3Json(
{'name': 'Eve', 'nickname': 'evie'},
ignoreUnknownFields: true,
);
print(p.name); // Eve
If your messages contain google.protobuf.Any, pass a TypeRegistry listing the possible message types via the typeRegistry parameter of both methods, so the library can resolve the type URLs.
The library also has writeToJson() and fromJson(), which use tag numbers as keys ({"1":"Bob","2":7}). That format is specific to the Dart library. Prefer proto3 JSON for anything other programs read.
Timestamps and other well-known types
The generated Timestamp class has helpers for converting to and from DateTime:
final ts = Timestamp.fromDateTime(DateTime.utc(2026, 1, 15, 10, 30));
print(ts.seconds); // 1768473000
print(ts.nanos); // 0
print(ts.toDateTime()); // 2026-01-15 10:30:00.000Z
print(ts.toDateTime(toLocal: true)); // same instant in local time
final now = Timestamp.fromDateTime(DateTime.now());
Other commonly used well-known types are Duration, Empty, Any, Struct (arbitrary JSON) and wrappers such as StringValue and Int32Value. Import them from package:protobuf/well_known_types/google/protobuf/duration.pb.dart and so on.
Immutability: freeze and rebuild
Generated messages are mutable. If you share a message between parts of a program and want to make sure nobody changes it, freeze it. A frozen message throws UnsupportedError on any modification, including its sub-messages and lists:
final config = Person(name: 'Alice', id: 1)..freeze();
print(config.isFrozen); // true
try {
config.name = 'Mallory';
} on UnsupportedError {
print('frozen');
}
// rebuild() copies a frozen message, applies changes, and freezes the copy.
final updated = config.rebuild((p) => p.id = 2);
print('${updated.name} ${updated.id}'); // Alice 2
print(config.id); // 1, the original is unchanged
rebuild() only works on frozen messages. To get an independent, mutable copy of any message, use deepCopy() (named clone() in older versions of the library).
Evolving a schema
Protobuf is designed so that old and new programs can exchange messages while the schema changes. The rules:
-
Adding fields is safe. Old code skips fields it doesn't know. New code sees default values when reading old messages.
-
Never reuse a tag number and never change a field's type. Doing so makes old data parse as garbage.
-
To remove a field, delete it and reserve its tag and name so nobody reuses them:
message Person { reserved 3; reserved "email"; // ... } -
Renaming a field is safe for the binary format (only tags are sent) but breaks proto3 JSON, which uses names.
-
Don't change a field to or from
repeatedor move existing fields into aoneof.
When the Dart library parses a field it doesn't know, it keeps the raw bytes in unknownFields and writes them back out in writeToBuffer(). A service using an older schema can therefore read a message, change one field and forward it without losing data it didn't understand:
final p = Person.fromBuffer(bytesFromNewerClient);
print(p.unknownFields.isEmpty); // false if the client sent new fields
p.name = p.name.toUpperCase();
forward(p.writeToBuffer()); // unknown fields are preserved
gRPC
gRPC is an RPC framework that uses protobuf for messages and HTTP/2 for transport. Define a service in a .proto file, for example protos/greeter.proto:
syntax = "proto3";
package greeter;
service Greeter {
rpc SayHello(HelloRequest) returns (HelloReply);
rpc CountDown(HelloRequest) returns (stream HelloReply);
}
message HelloRequest {
string name = 1;
}
message HelloReply {
string message = 1;
}
Add grpc: ^5.0.0 to your dependencies and pass the grpc option to the plugin:
protoc --dart_out=grpc:lib/src/generated -Iprotos protos/greeter.proto
Besides the message classes, this creates greeter.pbgrpc.dart with an abstract GreeterServiceBase class to implement on the server and a GreeterClient class for callers.
The server:
import 'package:grpc/grpc.dart';
import 'package:pbdemo/src/generated/greeter.pbgrpc.dart';
class GreeterService extends GreeterServiceBase {
@override
Future<HelloReply> sayHello(ServiceCall call, HelloRequest request) async {
return HelloReply(message: 'Hello, ${request.name}!');
}
@override
Stream<HelloReply> countDown(ServiceCall call, HelloRequest request) async* {
for (var i = 3; i > 0; i--) {
yield HelloReply(message: '$i...');
await Future.delayed(const Duration(milliseconds: 200));
}
yield HelloReply(message: 'Go, ${request.name}!');
}
}
Future<void> main() async {
final server = Server.create(services: [GreeterService()]);
await server.serve(port: 50051);
print('Listening on port ${server.port}');
}
The client:
import 'package:grpc/grpc.dart';
import 'package:pbdemo/src/generated/greeter.pbgrpc.dart';
Future<void> main() async {
final channel = ClientChannel(
'localhost',
port: 50051,
options: const ChannelOptions(
credentials: ChannelCredentials.insecure(),
),
);
final client = GreeterClient(channel);
try {
final reply = await client.sayHello(
HelloRequest(name: 'Dart'),
options: CallOptions(timeout: const Duration(seconds: 5)),
);
print(reply.message);
await for (final r in client.countDown(HelloRequest(name: 'Dart'))) {
print(r.message);
}
} on GrpcError catch (e) {
print('RPC failed: ${e.codeName} ${e.message}');
} finally {
await channel.shutdown();
}
}
Output:
Hello, Dart!
3...
2...
1...
Go, Dart!
ChannelCredentials.insecure() is only for local development. In production use ChannelCredentials.secure(), which uses TLS (see TLS and HTTPS). A server reports errors by throwing GrpcError, for example throw GrpcError.notFound('no such user'), and the client receives the same status code. In browsers, use GrpcWebClientChannel from package:grpc/grpc_web.dart, which talks to a gRPC-Web proxy.
Tips
- Keep
.protofiles in one place and generate code with a script (or aMakefiletarget) so everyone uses the sameprotocand plugin versions. - Use binary for storage and service-to-service traffic, and proto3 JSON where humans or JavaScript clients need to read the data.
- Start enums with an
..._UNSPECIFIED = 0value and prefix value names with the enum name, because enum values share a namespace within a.protopackage. - Use
optionalfor scalar fields where "unset" is meaningful, and check presence withhasX(). - Parsing untrusted input with
fromBuffer()throwsInvalidProtocolBufferExceptionon malformed data. Catch it at your system's boundaries. - Big messages take a while to decode. For large payloads in a Flutter app or server, decode in a background isolate with
Isolate.run(). See Isolates.