In this post, I will explain how to set up GraphQL tools to generate Dart classes, this method work for Flutter or any Dart project.

Project setup

Dependencies

# /pubspec.yaml
dev_dependencies:
  build_runner: ">=1.0.0 <2.0.0"
  gql_build: # Use latest version
  gql_code_builder: # Use latest version

Add your schema file

Add your schema file in /lib/schema.graphql.

To follow up with the same examples used in this tutorial, get the schema from here.

Setup build tools

In the root directory create a new file /build.yaml, and add the following code.

# /build.yaml
targets:
  $default:
    builders:
      gql_build|schema_builder:
        enabled: true
      gql_build|ast_builder:
        enabled: true
      gql_build|data_builder:
        enabled: true
        options:
          schema: app_package_name|lib/schema.graphql
      gql_build|var_builder:
        enabled: true
        options:
          schema: app_package_name|lib/schema.graphql
      gql_build|serializer_builder:
        enabled: true
        options:
          schema: app_package_name|lib/schema.graphql

Write your queries/mutations

You can place your queries/mutations files in any directory according to the app structure, I will put it in /lib/graphql.

Let’s write a simple query, a simple mutation, and a fragment. Note how we import fragments as comments.

# /lib/graphql/user_fragment.graphql
fragment UserFragment on User {
    id
    name
    username
    email
}
# /lib/graphql/get_users.graphql
#import "user_fragment.graphql"
query GetUsers {
  users {
    data {
      ...UserFragment
    }
  }
}
# /lib/graphql/update_user.graphql
#import "user_fragment.graphql"
mutation UpdateUser($id: ID!, $input: UpdateUserInput!) {
    updateUser(id: $id, input: $input) {
        ...UserFragment
    }
}

Build

Run the command flutter pub run build_runner build --delete-conflicting-outputs to generate Dart classes. The command wil take a minute, and you will see few new files in the /lib and /lib/graphql directories.

Do not worry about the content of the generated files, In the next blog post I will go through how to use theme.

FAQ

  1. Should I commit the generated files?
  2. NO, I mean YES. It’s up to you; but the common practice is to ignore the generated files.

  3. Do I have to run the build command evey time I change my graphql files?

  4. YES, or use the watch command like this flutter pub run build_runner watch --delete-conflicting-outputs.

  5. CanI see full project?

  6. Sure, it’s on my GitHub.