This is an opinionated code-generation tool from GraphQL to Dart/Flutter.

Overview

GraphQL Codegen

This is an opinionated code-generation tool from GraphQL to Dart/Flutter.

It'll allow you to generate Dart serializers and client helpers with minimal config. The framework makes no assumption on how you structure your fragments or queries, for each operation.graphql the framework will generate a operation.graphq.dart file containing dart classes.

Read more about the tool and motiation at the GraphQL Codegen deep-dive and on how you can structure your flutter apps with the tool on Structure your Flutter GraphQL apps.

The builder relies on json_serializable to generate the actual serializers, so in addition to the two files mentioned above, it'll also generate a operation.graphql.g.dart file.

The framework does not fetch your schema for you, so before you run this, you'll need to add your schema to your project.

Installation

Add graphql_codegen: to your dev_dependencies.

The project depends on json_serializable so read more on how to set this up here. It is also a builder, so you'll need to set up build_runner. Read more here.

Basic Usage

To generate dart classes from GraphQL schema, firstly you have to create a schema.graphql file and GraphQL document files.

For instance:

Given schema

# schema.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

and a query

# person.graphql

query FetchPerson($id: ID!) {
  fetch_person(id: $id) {
    name: full_name
  }
}

and then you can generate dart classes with:

$ dart run build_runner build

afterwards, you can parse the result with

// person.dart

import 'person.graphql.dart';

main () {
    final data = fetchDataFromSomewhereMaybeOuterSpace();
    final parsedData = QueryFetchPerson.fromJson(data);
    final name = parsedData.fetchPerson?.name;
    print(name);
}

Using fragments

Fragments are a great tool to re-use queries throughout your app. These are used to create "interfaces" which'll allow you to easily parse your data around. Given the schema above and the query

# parents_and_children.graphql

fragment PersonSummary on Person {
  full_name
}

query FetchParentsAndChildren {
  fetch_person(id: "1") {
    parents {
      ...PersonSummary
      nickname
    }

    children {
      ...PersonSummary
    }
  }
}

this will allow you to do the following

// parents_and_children.dart

import 'parents_and_children.graphql.dart';

printPerson(FragmentPersonSummary person) {
    print(person.fullName);
}

main () {
    final data = fetchDataFromTheVoid();
    final parsedData = QueryFetchParentsAndChildren.fromJson(data);
    for (final parent in parsedData?.fetchPerson.parents ?? []) {
        printPerson(parent);
        print(parent.dob);
    }
    for (final child in parsedData?.fetchPerson.children ?? []) {
        printPerson(child);
    }
}

The FragmentPersonSummary is an abstract class on the shape of

...
abstract class FragmentPersonSummary {
    String get fullName;
}
...

and will be available in the generated .graphql.dart file for the .graphql file containing the fragment.

Custom scalars

Out of the box, the standard fragmens are supported and mapped to relevant dart types. You can add new mappings for your custom scalars or overwrite existing configurations.

In the schema above, you can see that we have defined the ISODateTime scalar. In this example, it contains a string with an iso formatted date-time string. We would like to map this to darts DateTime type by adding the following configuration to the build.yaml file:

# build.yaml

targets:
  $default:
    builders:
      graphql_codegen:
        options:
          scalars:
            ISODateTime:
              type: DateTime
            JSON:
              type: Map
   

since json_serializable supports parsing DateTime from strings this is all we need to do.

Assume we want to use a custom date-time class instead (e.g. CustomDateTime) we can add

# build.yaml

targets:
  $default:
    builders:
      graphql_codegen:
        options:
          scalars:
            ISODateTime:
              type: CustomDateTime
              fromJsonFunctionName: customDateTimeFromJson
              toJsonFunctionName: customDateTimeToJson
              import: package:my_app/scalar.dart

and create a scalar.dart file with your converter functions and class.

// custom_date_time.dart
class CustomDateTime {
    final String datetime;

    CustomDateTime(this.datetime);
}

and

// scalar.dart

export 'custom_date_time.dart' show {CustomDateTime};

CustomDateTime customDateTimeFromJson(dynamic data) => CustomDateTime(data as String);
dynamic customDateTimeToJson(CustomDateTime time) => time.datetime;

and now all fields using ISODateTime will be a CustomDateTime instance.

Clients

Parsing data is all fine and well, but practically not extremly usable. Therefor, we can generate clients to call your API.

Clients can be enabled in the build.yaml file with:

# build.yaml

targets:
  $default:
    builders:
      graphql_codegen:
        options:
          clients:
            - graphql
            - graphql_flutter

Currently, we support two clients:

Client graphql

Once you've setup your graphql client (see pub.dev/packages/graphql), you can use GraphQL Codegen to generate new queries or mutators on the client.

With the query from above:

# person.graphql

query FetchPerson($id: ID!) {
  fetch_person(id: $id) {
    name: full_name
  }
}

we can now access the client:

import 'person.graphql.dart';


main () async {
    final client = GraphQLClient();
    final result = await client.queryFetchPerson(
        GQLOptionsQueryFetchPerson(
            variables: VariablesQueryFetchPerson(
                id: "1",
            ),
        ),
    );
    final parsedData = result.parsedBodyQueryFetchPerson;
    print(parsedData?.fetchPerson?.name);
}

Client graphql_flutter

Once you've setup your graphql_flutter client (see pub.dev/packages/graphql_flutter), you can use GraphQL Codegen to generate new Query or Mutation widgets.

With the query from above:

# person.graphql

query FetchPerson($id: ID!) {
  fetch_person(id: $id) {
    name: full_name
  }
}

we can query with the widget

import 'person.graphql.dart';
import 'package:flutter/widgets.dart';

class PersonWidget extends StatelessWidget {

    @override
    Widget build(BuildContext context) {
        return GQLFQueryFetchPerson(
            options: GQLOptionsQueryFetchPerson(
                variables: VariablesQueryFetchPerson(
                    id: 'id',
                ),
            ),
            builder: (result, {fetchMore, refetch}) {
                return Text(
                    result.parsedDataQueryFetchPerson?.fetchPerson?.name ?? '...loading'
                );
            }
        );
    }

}
You might also like...

This is tool to create 3D Models which can be used in Flutter Applications. Tool is developed completely using Flutter.

three_d_model_tool A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you start

Nov 8, 2022

INSTAGRAM CLONE - FRONTEND FLUTTER 2.5 + GRAPHQL + RIVERPOD

INSTAGRAM CLONE - FRONTEND FLUTTER 2.5 FLUTTER + GRAPHQL + RIVERPOD USER LOGIN SEE PROFILE EDIT PROFILE FOLLOW USER UNFOLLOW USER TOTAL FOLLOWING TOTA

Sep 2, 2022

flutter app to manage books and authors data using graphql on hasura.io

GraphQL Book Lisitngs with Proper Providers or without Providers. In this flutter project we use GraphQL with backend as hasura. Getting Started Pleas

Nov 7, 2022

Made with Clean architecture + TDD + GraphQL + flutter_bloc + CodeCov + GitHooks + GitHub Actions (CI/CD) and finally with 💙

Made with Clean architecture + TDD + GraphQL + flutter_bloc + CodeCov + GitHooks + GitHub Actions (CI/CD) and finally with 💙

Rick and Morty Info A simple app to demonstrate Clean Architecture with GraphQL and flutter_bloc Motivation In Martin Fowler's words, “Any fool can wr

Dec 25, 2022

💘 This is my Youtube tutorial of my Social Media App Generation Made in Flutter 💘

💘 Generation Tutorial 💘 ⌛ This is the project source code of my youtube video tutorial of ⌛ 💚 Flutter Social Media App Tutorial 2021 💚 📌 Tutorial

Nov 24, 2022

Router_generator is a flutter library for router generation

Router_generator is a flutter library for router generation

Sep 27, 2022

POC fit-generation

fit_generation POC for fit-generation Table of content Table of content Project Description Getting started Git commit rules Navigation Deep Linking N

Jun 3, 2022

Quickly is build as a tool to enhance your Flutter UI development experience and make code easier

Quickly is build as a tool to enhance your Flutter UI development experience and make code easier. It is highly inspired by Bootstrap and Tailwind CSS. It also provide lots of extension methods on String, List and Map.

Oct 24, 2022

Tool made in Dart that allows you to dynamically generate JSON files from data models written in Dart.

Dart JSON Generator Versión v1.1.1 Dart JSON Generator es una herramienta que permite generar archivos JSON a partir de mapas como modelos de datos en

Nov 23, 2022
Owner
United Traders
United Traders put together a simple and easy to use trading platform that gets you instant exposure to top foreign companies.
United Traders
A GraphQL client for Flutter, bringing all the features from a modern GraphQL client to one easy to use package. Built after react apollo

Flutter GraphQL Table of Contents Flutter GraphQL Table of Contents About this project Installation Usage GraphQL Provider [Graphql Link and Headers]

Snowball Digital 45 Nov 9, 2022
A GraphQL client for Flutter, bringing all the features from a modern GraphQL client to one easy to use package.

GraphQL Flutter ?? Bulletin See the v3 -> v4 Migration Guide if you're still on v3. Maintenance status: Low. Follow #762 for updates on the planned ar

Zino & Co. 3.1k Jan 5, 2023
A demo Project Showcasing HowTo use GraphQL to conect as a client to a GraphQL service.

graphql_demoapp A Flutter App to demonstrate how to work with GraphQL Server, connecting through our app as a client. Working with basic queries and m

Igor L Sambo 2 Nov 7, 2021
Flying Fish is full-stack Dart framework - a semi-opinionated framework for building applications exclusively using Dart and Flutter

Flying Fish is full-stack Dart framework - a semi-opinionated framework for building applications exclusively using Dart and Flutter.

Flutter Fish 3 Dec 27, 2022
An opinionated, community-driven set of lint rules for Dart and Flutter projects. Like pedantic but stricter

Lint for Dart/Flutter lint is a hand-picked, open-source, community-driven collection of lint rules for Dart and Flutter projects. The set of rules fo

Pascal Welsch 257 Jan 3, 2023
🎨 An opinionated, effective and correct way to provide multiple themes to your app.

theming This is an opinionated and effective way to provide multi-theme choice for your app. theming depends on provider and shared_preference for sta

Chinyeaka Chinonso 3 Nov 28, 2022
Simple Dart package with build-in code generation. It simplifies and speedup creation of cache mechanism for dart classes.

Simple Dart package with build-in code generation. It simplifies and speedup creation of cache mechanism for dart classes.

iteo 37 Jan 2, 2023
Create dart data classes easily, fast and without writing boilerplate or running code generation.

Dart Data Class Generator Create dart data classes easily, fast and without writing boilerplate or running code generation. Features The generator can

null 186 Feb 28, 2022
Automatic source code generation for Dart

Overview source_gen provides utilities for automated source code generation for Dart: A framework for writing Builders that consume and produce Dart c

Dart 418 Dec 30, 2022
A flutter plugin about qr code or bar code scan , it can scan from file、url、memory and camera qr code or bar code .Welcome to feedback your issue.

r_scan A flutter plugin about qr code or bar code scan , it can scan from file、url、memory and camera qr code or bar code .Welcome to feedback your iss

PengHui Li 112 Nov 11, 2022