In embed mode the generator writes raw triple-quoted Dart strings (r'''...''') so that
GraphQL variables like $id and newlines are preserved without Dart string interpolation.
Small builder to turn GraphQL .graphql files into Dart strings.
Two outputs are generated when you run build_runner:
- Per-file: For each
*.graphql, a sibling*.graphql.dartfile is generated with a Dart string (embed mode) or lazy loader (load mode). - Aggregate: One
lib/graphql/generatedOutputs/Queries.dartfile is created aggregating all discovered queries/mutations/subscriptions/fragments as constants or lazy getters.
Add to your app or package pubspec.yaml:
dev_dependencies:
build_runner: ^2.4.11
gql_gen:
path: ../gql_gen # or from pub when publishedIf you will use load mode (strings loaded at runtime), declare your .graphql assets:
flutter:
assets:
- lib/graphql/Create a gql_gen.yaml at your package root to customize discovery and behavior:
# gql_gen.yaml
mode: embed # or 'load'
include:
- lib/graphql/**/*.graphql
exclude: []
# When non-empty, disables per-file outputs and generates only the aggregate file.
# Note: Due to build_runner constraints the aggregate output path is fixed to
# lib/graphql/generatedOutputs/Queries.dart. To change it, edit build.yaml.
output_subdir: ""Notes:
- Output behavior:
- When
output_subdiris empty (default): only per-file outputs are generated next to each.graphqlfile. - When
output_subdiris non-empty: per-file outputs are disabled and only the aggregate file is generated. - Aggregate output path is fixed to
lib/graphql/generatedOutputs/Queries.dartbybuild.yaml. If you need a different path, change the mapping inbuild.yaml.
- When
dart run build_runner build
# or
flutter pub run build_runner buildGiven files:
lib/graphql/userModel.graphql(fragment)lib/graphql/GetUser.graphql(query)
You will get:
lib/graphql/GetUser.graphql.dartwith agetUserconstant (embed) orFuture<String> get getUser(load)lib/graphql/generatedOutputs/Queries.dartwith constants/getters likegetUserQuery,userFragment, etc.
Example (embed mode):
import 'package:your_app/graphql/generatedOutputs/Queries.dart';
void main() {
print(getUserQuery); // Raw GraphQL string
}Example (load mode):
import 'package:your_app/graphql/generatedOutputs/Queries.dart';
Future<void> run() async {
final doc = await getUserQuery; // Loaded from asset
print(doc);
}If you prefer per-file imports:
import 'package:your_app/graphql/GetUser.graphql.dart';
void main() {
print(getUser); // string or loader depending on mode
}