### Generate GraphQL Client Query Source: https://github.com/heftapp/graphql_codegen/blob/main/packages/graphql_codegen/README.md Example of using a generated GraphQL client to fetch data. Ensure the client is initialized and the query is correctly defined. ```graphql query FetchPerson($id: ID!) { fetch_person(id: $id) { name: full_name } } ``` ```dart import 'person.graphql.dart'; main () async { final client = GraphQLClient(); final result = await client.query$FetchPerson( Options$Query$FetchPerson( variables: Variables$Query$FetchPerson(id: "1"), ), ); final parsedData = result.parsedData; print(parsedData?.fetchPerson?.name); } ``` -------------------------------- ### Add Optional Dependencies for GraphQL Integration Source: https://github.com/heftapp/graphql_codegen/blob/main/packages/graphql_codegen/README.md Installs optional dependencies for integrating generated types with graphql, graphql_flutter, and flutter_hooks. ```sh flutter pub add graphql graphql_flutter flutter_hooks ``` -------------------------------- ### Add GraphQL Codegen Dev Dependencies Source: https://context7.com/heftapp/graphql_codegen/llms.txt Install the graphql_codegen and build_runner packages as development dependencies. Optionally, add runtime dependencies for client integration. ```sh # Add dev dependencies flutter pub add --dev graphql_codegen build_runner # Add optional runtime dependencies for client integration flutter pub add graphql graphql_flutter flutter_hooks ``` -------------------------------- ### Add Dev Dependencies for GraphQL Codegen Source: https://github.com/heftapp/graphql_codegen/blob/main/packages/graphql_codegen/README.md Installs graphql_codegen and build_runner as development dependencies using Flutter. ```sh flutter pub add --dev graphql_codegen build_runner ``` -------------------------------- ### Generate GraphQL Flutter Query Widget Source: https://github.com/heftapp/graphql_codegen/blob/main/packages/graphql_codegen/README.md Example of using a generated Query widget for the graphql_flutter package. This widget handles the GraphQL query execution and displays data. ```dart import 'person.graphql.dart'; import 'package:flutter/widgets.dart'; class PersonWidget extends StatelessWidget { @override Widget build(BuildContext context) { return Query$FetchPerson$Widget( options: Options$Query$FetchPerson( variables: Variables$Query$FetchPerson(id: 'id'), ), builder: (result, {fetchMore, refetch}) { return Text( result.parsedData?.fetchPerson?.name ?? '...loading' ); } ); } } ``` -------------------------------- ### Generate GraphQL Flutter Query Hook Source: https://github.com/heftapp/graphql_codegen/blob/main/packages/graphql_codegen/README.md Example of using a generated useQuery hook for graphql_flutter. This hook simplifies data fetching and state management within Flutter applications. ```dart import 'person.graphql.dart'; import 'package:flutter/widgets.dart'; import 'flutter_hooks/flutter_hooks.dart'; class PersonWidget extends HookWidget { @override Widget build(BuildContext context) { final result = useQuery$FetchPerson( Options$Query$FetchPerson( variables: Variables$Query$FetchPerson(id: 'id'), ), ); return Text(result.parsedData?.fetchPerson?.name ?? '...loading'); } } ``` -------------------------------- ### Flutter Hooks Integration for GraphQL Queries Source: https://context7.com/heftapp/graphql_codegen/llms.txt Utilize generated hooks with flutter_hooks for functional widget patterns when performing GraphQL queries. This example shows a simple text display of fetched data. ```dart import 'package:flutter/widgets.dart'; import 'package:flutter_hooks/flutter_hooks.dart'; import 'person.graphql.dart'; class PersonHookWidget extends HookWidget { @override Widget build(BuildContext context) { final result = useQuery$FetchPerson( Options$Query$FetchPerson( variables: Variables$Query$FetchPerson(id: 'id'), ), ); return Text(result.parsedData?.fetchPerson?.name ?? '...loading'); } } ``` -------------------------------- ### Configure GraphQL Codegen Clients Source: https://github.com/heftapp/graphql_codegen/blob/main/packages/graphql_codegen/README.md Enable GraphQL client generation by specifying client types in the build.yaml configuration file. ```yaml targets: $default: builders: graphql_codegen: options: clients: - graphql - graphql_flutter ``` -------------------------------- ### Configure Output Directory and Asset Path Source: https://github.com/heftapp/graphql_codegen/blob/main/packages/graphql_codegen/README.md Specify the output directory for generated files and the path to GraphQL assets. This configuration places generated files in `/lib/__generated` based on GraphQL files found in `graphql/**`. ```yaml targets: $default: builders: graphql_codegen: options: outputDirectory: /lib/__generated assetsPath: graphql/** ``` -------------------------------- ### GraphQL Code Generation Build Options Source: https://context7.com/heftapp/graphql_codegen/llms.txt A comprehensive list of build configuration options for graphql_codegen, including client types, scalar and enum configurations, typename handling, output directory, and more. ```yaml # build.yaml targets: $default: builders: graphql_codegen: options: clients: - graphql - graphql_flutter scalars: ISODateTime: type: DateTime enums: MyEnum: fallbackEnumValue: OTHER addTypename: true # Auto-add __typename (default: true) addTypenameExcludedPaths: - subscription.* outputDirectory: __generated # Output folder (default: ".") assetsPath: "lib/**.graphql" # GraphQL file glob generatedFileHeader: "// GENERATED FILE\n" scopes: - "**.graphql" # Multiple schema support namingSeparator: "$" # Class name separator (default: "$") extraKeywords: - String # Fields to escape as keywords disableCopyWithGeneration: false allowMissingNullableKeysInFromJson: false setOperationName: false ``` -------------------------------- ### Configure Multiple Schema Support Source: https://context7.com/heftapp/graphql_codegen/llms.txt Enable support for multiple GraphQL schemas by specifying glob patterns for schema files in the build.yaml configuration. ```yaml # build.yaml targets: $default: builders: graphql_codegen: options: scopes: - lib/schema1/** - lib/schema2/** ``` -------------------------------- ### Configure GraphQL Client in build.yaml Source: https://context7.com/heftapp/graphql_codegen/llms.txt Configure the graphql codegen builder in your build.yaml to enable client integrations for graphql and graphql_flutter. ```yaml # build.yaml targets: $default: builders: graphql_codegen: options: clients: - graphql - graphql_flutter ``` -------------------------------- ### Run GraphQL Codegen Build Source: https://github.com/heftapp/graphql_codegen/blob/main/packages/graphql_codegen/README.md Executes the build_runner to generate Dart classes from GraphQL schema and document files. ```sh dart run build_runner build ``` -------------------------------- ### Manipulate GraphQL Cache with Fragments Source: https://github.com/heftapp/graphql_codegen/blob/main/packages/graphql_codegen/README.md Demonstrates reading and writing fragments to the GraphQL cache using generated methods. Requires fragment definition and appropriate ID fields for cache access. ```graphql fragment PersonSummary on Person { name } ``` ```dart main () { // ... final person = client.readFragment$PersonSummary( idFields: {'__typename': 'Person', 'id': '1'}, ); assert(person != null); client.writeFragment$PersonSummary( idFields: {'__typename': 'Person', 'id': '1'}, data: person.copyWith(name: 'Kurt'), ); } ``` -------------------------------- ### Type-Safe GraphQL Query with Extension Method Source: https://context7.com/heftapp/graphql_codegen/llms.txt Execute type-safe GraphQL queries using generated extension methods on GraphQLClient. Ensure the graphql package is imported and the client is initialized. ```dart import 'package:graphql/client.dart'; import 'person.graphql.dart'; void main() async { final client = GraphQLClient( link: HttpLink("https://api.example.com/graphql"), cache: GraphQLCache(store: InMemoryStore()), ); // Type-safe query with generated extension method final result = await client.query$FetchPerson( Options$Query$FetchPerson( variables: Variables$Query$FetchPerson(id: "1"), ), ); // Access parsed data directly final person = result.parsedData?.fetchPerson; print(person?.name); // Handle errors if (result.hasException) { print('Error: ${result.exception}'); } } ``` -------------------------------- ### Define Subscription Operation Source: https://context7.com/heftapp/graphql_codegen/llms.txt Define a GraphQL subscription operation in a .graphql file to receive real-time updates. ```graphql # lib/subscriptions.graphql subscription WatchPerson($id: ID) { watch_person(id: $id) { full_name } } ``` -------------------------------- ### Subscribe to GraphQL Updates Source: https://context7.com/heftapp/graphql_codegen/llms.txt Use the generated client to subscribe to GraphQL real-time updates using a WebSocket link and process incoming data streams. ```dart import 'package:graphql/client.dart'; import 'subscriptions.graphql.dart'; void main() { final client = GraphQLClient( link: WebSocketLink("wss://api.example.com/graphql"), cache: GraphQLCache(store: InMemoryStore()), ); // Subscribe with type-safe stream final stream = client.subscribe$WatchPerson( Options$Subscription$WatchPerson( variables: Variables$Subscription$WatchPerson(id: '1'), ), ); stream.listen((result) { final person = result.parsedData?.watchPerson; print('Updated: ${person?.full_name}'); }); } ``` -------------------------------- ### Change Output Directory Source: https://github.com/heftapp/graphql_codegen/blob/main/packages/graphql_codegen/README.md Specify a custom `outputDirectory` to control where generated Dart files are placed relative to the `.graphql` source files. ```yaml # build.yaml targets: $default: builders: graphql_codegen: options: outputDirectory: __generated ``` -------------------------------- ### Define GraphQL Mutation Source: https://context7.com/heftapp/graphql_codegen/llms.txt Define a GraphQL mutation in a .graphql file. This mutation takes an ID and an optional name, and returns the updated full name. ```graphql # lib/mutations.graphql mutation UpdatePerson($id: ID!, $name: String) { update_person(id: $id, full_name: $name) { full_name } } ``` -------------------------------- ### Configure Multiple Schemas with Scopes Source: https://github.com/heftapp/graphql_codegen/blob/main/packages/graphql_codegen/README.md Enable independent analysis for multiple GraphQL schemas by defining scopes. Each scope points to a directory containing schema files, and the generator processes them in isolation. ```yaml targets: $default: builders: graphql_codegen: options: scopes: - lib/schema1/** - lib/schema2/** ``` -------------------------------- ### GraphQL Schema with Named Fragments Source: https://github.com/heftapp/graphql_codegen/blob/main/packages/graphql_codegen/README.md Defines named fragments for 'PersonalAccount' and 'BusinessAccount' to simplify queries. ```graphql fragment PersonalAccount on PersonalAccount { personName } fragment BusinessAccount on BusinessAccount { businessName } ``` -------------------------------- ### Specify Extra Keywords Source: https://github.com/heftapp/graphql_codegen/blob/main/packages/graphql_codegen/README.md Provide a list of extra keywords that might conflict with generated code. This option helps prevent errors when field or type names clash with reserved words. ```yaml # build.yaml targets: $default: builders: graphql_codegen: options: extraKeywords: - String ``` -------------------------------- ### GraphQL Cache Read and Write Operations Source: https://context7.com/heftapp/graphql_codegen/llms.txt Directly interact with the GraphQL cache to read and write fragments and queries. This allows for efficient data management and updates. ```dart import 'package:graphql/client.dart'; import 'person.graphql.dart'; import 'fragments.graphql.dart'; void main() { final client = GraphQLClient( link: HttpLink("https://api.example.com/graphql"), cache: GraphQLCache(store: InMemoryStore()), ); // Read fragment from cache final person = client.readFragment$PersonSummary( idFields: {'__typename': 'Person', 'id': '1'}, ); if (person != null) { // Update fragment in cache using copyWith client.writeFragment$PersonSummary( idFields: {'__typename': 'Person', 'id': '1'}, data: person.copyWith(name: 'Updated Name'), ); } // Read/write full queries final cachedQuery = client.readQuery$FetchPerson( variables: Variables$Query$FetchPerson(id: '1'), ); if (cachedQuery != null) { client.writeQuery$FetchPerson( variables: Variables$Query$FetchPerson(id: '1'), data: cachedQuery, ); } } ``` -------------------------------- ### Enable Typename Field Generation Source: https://github.com/heftapp/graphql_codegen/blob/main/packages/graphql_codegen/README.md Configure `addTypename` to true to include the `__typename` field in all selection sets for improved caching. Be aware of potential spec violations with subscriptions. ```yaml addTypenameExcludedPaths: - subscription.* ``` -------------------------------- ### Process Fragment Data in Dart Source: https://github.com/heftapp/graphql_codegen/blob/main/packages/graphql_codegen/README.md Demonstrates processing parsed GraphQL data that includes fragments, accessing fields from the fragment types and nested objects. ```dart // parents_and_children.dart import 'parents_and_children.graphql.dart'; printPerson(FragmentPersonSummary person) { print(person.fullName); } main () { final data = fetchDataFromTheVoid(); final parsedData = Query$FetchParentsAndChildren.fromJson(data); for (final parent in parsedData?.fetchPerson.parents ?? []) { printPerson(parent); print(parent.dob); } for (final child in parsedData?.fetchPerson.children ?? []) { printPerson(child); } } ``` -------------------------------- ### GraphQL Fragment Definition Source: https://github.com/heftapp/graphql_codegen/blob/main/packages/graphql_codegen/README.md Defines a fragment 'PersonSummary' on the 'Person' type to extract the 'full_name' field for reusability. ```graphql fragment PersonSummary on Person { full_name } ``` -------------------------------- ### Dart Code for Handling Inline Fragment Data Source: https://github.com/heftapp/graphql_codegen/blob/main/packages/graphql_codegen/README.md Dart code demonstrating how to handle data from inline fragments using type checks. ```dart void printAccount(Query$FetchAccount$account account) { if (account is Query$FetchAccount$account$$PersonalAccount) print(account.personName); if (account is Query$FetchAccount$account$$BusinessAccount) print(account.businessName); } void printQuery(Query$FetchAccount query) { printAccount(query.account); } ``` -------------------------------- ### Define GraphQL Fragment Source: https://context7.com/heftapp/graphql_codegen/llms.txt Define a GraphQL fragment in a .graphql file to create reusable interfaces for shared field access across multiple queries. This promotes code reuse and maintainability. ```graphql # lib/parents_and_children.graphql fragment PersonSummary on Person { full_name } query FetchParentsAndChildren { fetch_person(id: "1") { parents { ...PersonSummary nickname } children { ...PersonSummary } } } ``` -------------------------------- ### Dart Code using `when` and `maybeWhen` for Union Types Source: https://github.com/heftapp/graphql_codegen/blob/main/packages/graphql_codegen/README.md Demonstrates using `when` and `maybeWhen` methods to handle union types without explicit type checks. ```dart void printAccount(Query$FetchAccount$account account) { // specify all the cases (and an else in case there's a new type in the response that wasn't previously known) account.when( personalAccount: (personalAccount) => print(personalAccount.personName), businessAccount: (businessAccount) => print(businessAccount.businessName), orElse: () => print('Some other unexpected type'), ) // specify only the cases you want to handle (and an else) account.maybeWhen( personalAccount: (personalAccount) => print(personalAccount.personName), orElse: () => print('Anything else, including BusinessAccount'), ) } void printQuery(Query$FetchAccount query) { printAccount(query.account); } ``` -------------------------------- ### GraphQL Query with Fragment Source: https://github.com/heftapp/graphql_codegen/blob/main/packages/graphql_codegen/README.md Defines a query that fetches a person and includes nested fragments for parents and children, utilizing the 'PersonSummary' fragment. ```graphql query FetchParentsAndChildren { fetch_person(id: "1") { parents { ...PersonSummary nickname } children { ...PersonSummary } } } ``` -------------------------------- ### Define GraphQL Schema Source: https://context7.com/heftapp/graphql_codegen/llms.txt Define your GraphQL schema, including types, fields, and custom scalars, in a .graphql file. This schema will be used for code generation. ```graphql # lib/schema.graphql type Query { fetch_person(id: ID!): Person } type Person { full_name: String! nickname: String website: URL date_of_birth: ISODateTime parents: [Person!] children: [Person!] } scalar ISODateTime scalar URL ``` -------------------------------- ### Add Generated File Header Source: https://github.com/heftapp/graphql_codegen/blob/main/packages/graphql_codegen/README.md Customize the header comment at the beginning of generated `.graphql.dart` files. This can be used to add ignore directives for linters or other metadata. ```yaml targets: $default: builders: graphql_codegen: options: generatedFileHeader: "// GENERATED FILE\n// DO NOT MODIFY\n" ``` ```yaml generatedFileHeader: "// ignore_for_file: type=lint\n" ``` -------------------------------- ### Flutter Query Widget Integration Source: https://context7.com/heftapp/graphql_codegen/llms.txt Integrate GraphQL queries into Flutter widgets using generated Query widgets for declarative data fetching. Handles loading and error states. ```dart import 'package:flutter/widgets.dart'; import 'person.graphql.dart'; class PersonWidget extends StatelessWidget { @override Widget build(BuildContext context) { return Query$FetchPerson$Widget( options: Options$Query$FetchPerson( variables: Variables$Query$FetchPerson(id: 'id'), ), builder: (result, {fetchMore, refetch}) { if (result.isLoading) { return Text('Loading...'); } if (result.hasException) { return Text('Error: ${result.exception}'); } return Text(result.parsedData?.fetchPerson?.name ?? 'Unknown'); }, ); } } ``` -------------------------------- ### Configure Custom Enum Fallback Value Source: https://github.com/heftapp/graphql_codegen/blob/main/packages/graphql_codegen/README.md Specify an existing enum value to be used as a fallback for unknown enum values, preventing app breakage. ```yaml # build.yaml targets: $default: builders: graphql_codegen: options: enums: MyEnum: fallbackEnumValue: OTHER ``` -------------------------------- ### Exclude Generated Files from Analysis Source: https://github.com/heftapp/graphql_codegen/blob/main/packages/graphql_codegen/README.md Configure `analysis_options.yaml` to exclude generated files from static analysis, preventing potential lint warnings. ```yaml analyzer: exclude: - lib/**/__generated__/* ``` -------------------------------- ### Define GraphQL Query Source: https://context7.com/heftapp/graphql_codegen/llms.txt Define a GraphQL query in a .graphql file. The generated Dart code will provide type-safe access to the query results. ```graphql # lib/person.graphql query FetchPerson($id: ID!) { fetch_person(id: $id) { name: full_name } } ``` -------------------------------- ### Type-Safe GraphQL Mutation Operation Source: https://context7.com/heftapp/graphql_codegen/llms.txt Execute type-safe GraphQL mutations using generated extension methods. The `onCompleted` callback provides parsed data upon successful mutation. ```dart import 'package:graphql/client.dart'; import 'mutations.graphql.dart'; void main() async { final client = GraphQLClient( link: HttpLink("https://api.example.com/graphql"), cache: GraphQLCache(store: InMemoryStore()), ); final result = await client.mutate$UpdatePerson( Options$Mutation$UpdatePerson( variables: Variables$Mutation$UpdatePerson(id: "1"), onCompleted: (data, parsed) { print('Updated: ${parsed?.updatePerson?.full_name}'); }, ), ); print(result.parsedData?.updatePerson?.full_name); } ``` -------------------------------- ### GraphQL Schema Definition Source: https://github.com/heftapp/graphql_codegen/blob/main/packages/graphql_codegen/README.md Defines a GraphQL schema including types, queries, and custom scalars like ISODateTime and URL. ```graphql type Query { fetch_person(id: ID!): Person } type Person { full_name: String! nickname: String website: URL date_of_birth: ISODateTime parents: [Person!] siblings: [Person!] children: [Person!] } scalar ISODateTime scalar URL ``` -------------------------------- ### Configure Custom Scalar Types Source: https://context7.com/heftapp/graphql_codegen/llms.txt Define custom scalar types in build.yaml, specifying their Dart type, and optional fromJson/toJson functions and import paths. ```yaml # build.yaml targets: $default: builders: graphql_codegen: options: scalars: ISODateTime: type: DateTime URL: type: String CustomDateTime: type: CustomDateTime fromJsonFunctionName: customDateTimeFromJson toJsonFunctionName: customDateTimeToJson import: package:my_app/scalars.dart JSON: type: Map ``` -------------------------------- ### GraphQL Query using Named Fragments Source: https://github.com/heftapp/graphql_codegen/blob/main/packages/graphql_codegen/README.md A GraphQL query that utilizes named fragments for fetching data from union types. ```graphql query FetchAccount { account { ...BusinessAccount ...PersonalAccount } } ``` -------------------------------- ### GraphQL Query with Inline Fragments Source: https://github.com/heftapp/graphql_codegen/blob/main/packages/graphql_codegen/README.md A GraphQL query that uses inline fragments to fetch data from different types within a union. ```graphql query FetchAccount { account { ... on PersonalAccount { personName } ... on BusinessAccount { businessName } } } ``` -------------------------------- ### Dart Code for Handling Named Fragment Data Source: https://github.com/heftapp/graphql_codegen/blob/main/packages/graphql_codegen/README.md Dart code demonstrating how to handle data from named fragments using type checks. ```dart void printAccount(Query$FetchAccount$account account) { if (account is Fragment$PersonalAccount) print(account.personName); if (account is Fragment$BusinessAccount) print(account.businessName); } void printQuery(Query$FetchAccount query) { printAccount(query.account); } ``` -------------------------------- ### Configure Custom Scalar Type Mapping Source: https://github.com/heftapp/graphql_codegen/blob/main/packages/graphql_codegen/README.md Map custom scalar types like ISODateTime to Dart types (e.g., String or DateTime) in the build.yaml file. ```yaml targets: $default: builders: graphql_codegen: options: scalars: ISODateTime: type: String JSON: type: Map ``` ```yaml targets: $default: builders: graphql_codegen: options: scalars: ISODateTime: type: DateTime JSON: type: Map ``` -------------------------------- ### Configure Custom Enum Serialization Source: https://github.com/heftapp/graphql_codegen/blob/main/packages/graphql_codegen/README.md Map GraphQL enums to custom Dart enum types, specifying conversion function names and import paths. ```yaml # build.yaml targets: $default: builders: graphql_codegen: options: enums: GraphQLEnum: type: DartEnum fromJsonFunctionName: fromJson toJsonFunctionName: toJson import: package:my_app/enum.dart ``` -------------------------------- ### Configure Custom Scalar Type Source: https://github.com/heftapp/graphql_codegen/blob/main/packages/graphql_codegen/README.md Define custom scalar types by specifying their Dart type, fromJson/toJson function names, and import path. ```yaml targets: $default: builders: graphql_codegen: options: scalars: ISODateTime: type: CustomDateTime fromJsonFunctionName: customDateTimeFromJson toJsonFunctionName: customDateTimeToJson import: package:my_app/scalar.dart ``` -------------------------------- ### Parse GraphQL Query Result in Dart Source: https://github.com/heftapp/graphql_codegen/blob/main/packages/graphql_codegen/README.md Demonstrates parsing a JSON response from a GraphQL query into generated Dart classes and accessing specific fields. ```dart // person.dart import 'person.graphql.dart'; main () { final data = fetchDataFromSomewhereMaybeOuterSpace(); final parsedData = Query$FetchPerson.fromJson(data); final name = parsedData.fetchPerson?.name; print(name); } ``` -------------------------------- ### GraphQL Query Definition Source: https://github.com/heftapp/graphql_codegen/blob/main/packages/graphql_codegen/README.md Defines a GraphQL query to fetch a person's full name, aliasing 'full_name' to 'name' in the result. ```graphql query FetchPerson($id: ID!) { fetch_person(id: $id) { name: full_name } } ``` -------------------------------- ### Implement Custom Enum Converters Source: https://github.com/heftapp/graphql_codegen/blob/main/packages/graphql_codegen/README.md Provide Dart functions to serialize and deserialize custom enum values. ```dart // enum.dart enum DartEnum { foo, bar, baz } DartEnum fromJson(String v) { switch(v) { case 'FOO': return DartEnum.foo; case 'BAR': return DartEnum.bar; default: return DartEnum.baz; } } String toJson(DartEnum v) { switch(v) { case DartEnum.foo: return 'FOO'; case DartEnum.bar: return 'BAR'; case DartEnum.baz: return 'BAZ'; } } ``` -------------------------------- ### Generate Immutable Data Updates with copyWith Source: https://context7.com/heftapp/graphql_codegen/llms.txt Utilize the generated copyWith method to create modified copies of data objects, ensuring immutability and preserving the original object. ```dart import 'person.graphql.dart'; void main() { final person = Query$FetchPerson$fetchPerson( name: 'John Doe', nickname: 'Johnny', ); // Create modified copy final updated = person.copyWith.call( name: 'Jane Doe', nickname: null, // Explicitly set to null ); print(updated.name); // Output: Jane Doe print(updated.nickname); // Output: null // Original unchanged print(person.name); // Output: John Doe } ``` -------------------------------- ### GraphQL Schema with Union Type Source: https://github.com/heftapp/graphql_codegen/blob/main/packages/graphql_codegen/README.md Defines a schema with a union type 'Account' that can be either 'PersonalAccount' or 'BusinessAccount'. ```graphql type Query { account: Account! } union Account = PersonalAccount | BusinessAccount type PersonalAccount { personName: String! } type BusinessAccount { businessName: String! } ``` -------------------------------- ### Handle Nullable Input Fields Source: https://github.com/heftapp/graphql_codegen/blob/main/packages/graphql_codegen/README.md When constructing input objects, `null` fields are omitted by default. To explicitly set a nullable field to `null`, use the `copyWith` function. ```dart Input$I(s: "Foo").toJson(); // {"s": "Foo"} Input$I(s: "Foo", b: null).toJson(); // {"s": "Foo"} Input$I(s: "Foo", b: false).toJson(); // {"s": "Foo", "b": false} Input$I(s: "Foo").copyWith(b: null).toJson(); // {"s": "Foo", "b": null} ``` -------------------------------- ### Generate and Use Type-Safe Query Data Source: https://context7.com/heftapp/graphql_codegen/llms.txt After running `dart run build_runner build`, generated Dart classes can be used to parse JSON responses and access fields with type safety. The generated classes also support JSON serialization. ```dart // After running: dart run build_runner build import 'person.graphql.dart'; void main() { // Parse JSON response into type-safe class final data = {'fetchPerson': {'name': 'John Doe', '__typename': 'Person'}, '__typename': 'Query'}; final parsedData = Query$FetchPerson.fromJson(data); // Access fields with full type safety final name = parsedData.fetchPerson?.name; print(name); // Output: John Doe // Serialize back to JSON final json = parsedData.toJson(); print(json); // Output: {fetchPerson: {name: John Doe, __typename: Person}, __typename: Query} } ``` -------------------------------- ### Custom Enum Implementation Source: https://context7.com/heftapp/graphql_codegen/llms.txt Implement custom enum logic in Dart, including fromJson and toJson functions to handle GraphQL enum values. ```dart // lib/enum.dart enum DartEnum { foo, bar, baz } DartEnum fromJson(String v) { switch(v) { case 'FOO': return DartEnum.foo; case 'BAR': return DartEnum.bar; default: return DartEnum.baz; } } String toJson(DartEnum v) { switch(v) { case DartEnum.foo: return 'FOO'; case DartEnum.bar: return 'BAR'; case DartEnum.baz: return 'BAZ'; } } ``` -------------------------------- ### Implement Custom Scalar Converters Source: https://github.com/heftapp/graphql_codegen/blob/main/packages/graphql_codegen/README.md Provide Dart functions to convert between JSON and your custom scalar type. ```dart // scalar.dart class CustomDateTime { final DateTime dt; CustomDateTime(this.dt); } CustomDateTime customDateTimeFromJson(dynamic data) => CustomDateTime(DateTime(data as String)); dynamic customDateTimeToJson(CustomDateTime time) => time.dt.toIso8601String(); ``` -------------------------------- ### Custom Scalar Implementation Source: https://context7.com/heftapp/graphql_codegen/llms.txt Provide Dart implementations for custom scalar types, including fromJson and toJson functions if specified in build.yaml. ```dart // lib/scalars.dart class CustomDateTime { final DateTime dt; CustomDateTime(this.dt); } CustomDateTime customDateTimeFromJson(dynamic data) => CustomDateTime(DateTime.parse(data as String)); dynamic customDateTimeToJson(CustomDateTime time) => time.dt.toIso8601String(); ``` -------------------------------- ### Define GraphQL Union Types and Fragments Source: https://context7.com/heftapp/graphql_codegen/llms.txt Define union types in your schema and corresponding fragments for each member type. This enables type-safe handling of union types in your generated Dart code. ```graphql # lib/schema.graphql type Query { account: Account! } union Account = PersonalAccount | BusinessAccount type PersonalAccount { personName: String! } type BusinessAccount { businessName: String! } ``` ```graphql # lib/account.graphql fragment PersonalAccount on PersonalAccount { personName } fragment BusinessAccount on BusinessAccount { businessName } query FetchAccount { account { ...PersonalAccount ...BusinessAccount } } ``` -------------------------------- ### Change Naming Separator Source: https://github.com/heftapp/graphql_codegen/blob/main/packages/graphql_codegen/README.md Customize the separator used in generated class names to avoid conflicts with other libraries. The default separator is `$`, but it can be changed to other strings like `___`. ```yaml # build.yaml targets: $default: builders: graphql_codegen: options: namingSeparator: "___" ``` -------------------------------- ### Use Fragment Interfaces in Dart Source: https://context7.com/heftapp/graphql_codegen/llms.txt Generated fragment classes provide reusable interfaces that can be used to access shared fields. This allows for type-safe access to fields defined in the fragment, even when dealing with different query structures. ```dart import 'parents_and_children.graphql.dart'; // Fragment generates a reusable interface void printPerson(Fragment$PersonSummary person) { print(person.fullName); } void main() { final data = { 'fetchPerson': { 'parents': [ {'full_name': 'Jane Doe', 'nickname': 'Mom', '__typename': 'Person'} ], 'children': [ {'full_name': 'Baby Doe', '__typename': 'Person'} ], '__typename': 'Person' }, '__typename': 'Query' }; final parsedData = Query$FetchParentsAndChildren.fromJson(data); // Both parents and children implement Fragment$PersonSummary for (final parent in parsedData.fetchPerson?.parents ?? []) { printPerson(parent); // Output: Jane Doe print(parent.nickname); // Output: Mom (parent-specific field) } for (final child in parsedData.fetchPerson?.children ?? []) { printPerson(child); // Output: Baby Doe } } ``` -------------------------------- ### Configure Custom Enum Generation Source: https://context7.com/heftapp/graphql_codegen/llms.txt Override default enum generation by specifying custom Dart types, fromJson/toJson functions, and import paths in build.yaml. A fallback value can be set for unknown enum values. ```yaml # build.yaml targets: $default: builders: graphql_codegen: options: enums: GraphQLEnum: type: DartEnum fromJsonFunctionName: fromJson toJsonFunctionName: toJson import: package:my_app/enum.dart MyEnum: fallbackEnumValue: OTHER ``` -------------------------------- ### Handle Union Types with Pattern Matching in Dart Source: https://context7.com/heftapp/graphql_codegen/llms.txt Use the `when` and `maybeWhen` methods on generated union types for type-safe pattern matching. Traditional type checking also remains a valid option. ```dart import 'account.graphql.dart'; void printAccount(Query$FetchAccount$account account) { // Type-safe pattern matching account.when( personalAccount: (personal) => print('Personal: ${personal.personName}'), businessAccount: (business) => print('Business: ${business.businessName}'), orElse: () => print('Unknown account type'), ); // Or handle only specific cases account.maybeWhen( personalAccount: (personal) => print(personal.personName), orElse: () => print('Not a personal account'), ); // Traditional type checking also works if (account is Fragment$PersonalAccount) { print(account.personName); } } void main() { final data = { 'account': {'personName': 'John', '__typename': 'PersonalAccount'}, '__typename': 'Query' }; final query = Query$FetchAccount.fromJson(data); printAccount(query.account); // Output: Personal: John } ``` -------------------------------- ### Exclude Paths from Typename Generation Source: https://github.com/heftapp/graphql_codegen/blob/main/packages/graphql_codegen/README.md Use `addTypenameExcludedPaths` to prevent the `__typename` field from being added to specific queries, mutations, subscriptions, or fragments. ```yaml addTypenameExcludedPaths: - subscription ``` ```yaml addTypenameExcludedPaths: - Foo ``` ```yaml addTypenameExcludedPaths: - subscription.bar ``` ```yaml addTypenameExcludedPaths: - subscription.* ``` ```yaml addTypenameExcludedPaths: - **.bar ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.