Search code examples
flutterdartprotocol-buffersgrpc-dart

Import and use protobufs outside of lib directory - dart


I am trying to build a web application with with Flutter for the frontend, go for the backend and gRPC as the communication protocol. In an effort to avoid using identical protobufs in 2 different directories, I refactored the protobufs and compiled them into a third directory outside of the client and server folders (all within the same repo). Now I'm having trouble accessing the compiled dart protobufs from the client code. Here is my folder structure:

.
|-- client/
  |-- pubspec.yaml
|-- protos/
  |-- dart_protos/
    |-- .dart_tool/
    |-- .packages
    |-- cards.pb.dart
    |-- cards.pbenum.dart
    |-- cards.pbjson.dart
    |-- cards.pbserver.dart
    |-- pubspec.lock
    |-- pubscpec.yaml
  |-- go_protos/
  |-- cards.proto

|-- server/

Here is how I am defining my dependencies in my client/pubspec.yaml

dependencies:
  flutter:
    sdk: flutter
  recase: ^4.0.0
  search_choices: ^2.0.7
  tcb_protos:
    path: ../protos/dart_protos

My protos/dart_protos/pubspec.yaml:

name: tcb_protos
environment:
  sdk: ">=2.0.0-dev.68.0 <3.0.0"
dependencies:
  protobuf: ^1.1.4
  protoc_plugin: ^19.3.1

And how I am importing the protobuf:

import 'package:tcb_protos/cards.pb.dart';

So I am running into a couple of issues:

  1. I am getting Target of URI hasn't been generated: 'package:tcb_protos/cards.pb.dart'. on the import
  2. I am unable to use the protobuf based on the import, and VSCode's intellisense isn't working on the package (which I am assuming is because either the package definition or import is wrong)

How can I use the protobuf in my Flutter widgets?


Solution

  • You need to have the proto .pb.dart files inside a lib/ folder.

    I made a small example here: https://github.com/sigurdm/shared_proto_example

    If you want to have protos in different packages that reference each other, that is currently not supported: https://github.com/google/protobuf.dart/issues/295