graphql_flutter 0.4.0 copy "graphql_flutter: ^0.4.0" to clipboard
graphql_flutter: ^0.4.0 copied to clipboard

outdated

A GraphQL client for Flutter.

GraphQL Flutter #

version MIT License All Contributors PRs Welcome

Watch on GitHub Star on GitHub

Table of Contents #

Installation #

First depend on the library by adding this to your packages pubspec.yaml:

dependencies:
  graphql_flutter: ^0.4.0

Now inside your Dart code you can import it.

import 'package:graphql_flutter/graphql_flutter.dart';

Usage #

To use the client it first needs to be initialzed with an endpoint and cache. If your endpoint requires authentication you can provide it to the client by calling the setter apiToken on the Client class.

For this example we will use the public GitHub API.

...

import 'package:graphql_flutter/graphql_flutter.dart';

void main() async {
  client = new Client(
    endPoint: 'https://api.github.com/graphql',
    cache: new InMemoryCache(), // currently the only cache type we have implemented.
  );
  client.apiToken = '<YOUR_GITHUB_PERSONAL_ACCESS_TOKEN>';

  ...
}

...

Queries #

Creating a query, is as simple as creating a multiline string:

String readRepositories = """
  query ReadRepositories(\$nRepositories) {
    viewer {
      repositories(last: \$nRepositories) {
        nodes {
          id
          name
          viewerHasStarred
        }
      }
    }
  }
"""
    .replaceAll('\n', ' ');

In your widget:

...

new Query(
  readRepositories, // this is the query you just created
  variables: {
    'nRepositories': 50,
  },
  pollInterval: 10, // optional
  builder: ({
    bool loading,
    var data,
    String error,
  }) {
    if (error != '') {
      return new Text(error);
    }

    if (loading) {
      return new Text('Loading');
    }

    // it can be either Map or List
    List repositories = data['viewer']['repositories']['nodes'];

    return new ListView.builder(
      itemCount: repositories.length,
      itemBuilder: (context, index) {
        final repository = repositories[index];

        return new Text(repository['name']);
    });
  },
);

...

Mutations #

Again first create the mutation string string:

String addStar = """
  mutation AddStar(\$starrableId: ID!) {
    addStar(input: {starrableId: \$starrableId}) {
      starrable {
        viewerHasStarred
      }
    }
  }
"""
    .replaceAll('\n', ' ');

The syntax for mutations fairly similar to those of a query. The only diffence is that the first argument of the builder function is the mutation function. Just call it to trigger the mutations (Yeah we deliberetly stole this from react-apollo.)

...

new Mutation(
  addStar,
  builder: (
    runMutation, { // you can name it whatever you like
    bool loading,
    var data,
    String error,
}) {
  return new FloatingActionButton(
    onPressed: () => runMutation({
      'starrableId': <A_STARTABLE_REPOSITORY_ID>,
    }),
    tooltip: 'Increment',
    child: new Icon(Icons.edit),
  );
}),

...

Offline Cache #

The in-memory cache can autmaticly be saved to and restored from offline storage. Setting it up is as easy as wrapping your app with the CacheProvider widget.

...

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new CacheProvider(
      child: new MaterialApp(
        title: 'Flutter Demo',
        theme: new ThemeData(
          primarySwatch: Colors.blue,
        ),
        home: new MyHomePage(title: 'Flutter Demo Home Page'),
      ),
    );
  }
}

...

Roadmap #

This is currently our roadmap, please feel free to request additions/changes.

Feature Progress
Basic queries
Basic mutations
Query variables
Mutation variables
Query polling
In memory caching
Offline caching
Optimistic results 🔜
Client state management 🔜

Contributing #

Feel free to open a PR with any suggetions! We'll be actively working on the library ourselfs.

Contributors #

Thanks goes to these wonderful people (emoji key):


Eustatiu Dima

💻 📖 💡 🤔 👀

Zino Hofmann

💻 📖 💡 🤔 👀

This project follows the all-contributors specification. Contributions of any kind are welcome!