graphql_flutter 0.6.0

  • README.md
  • CHANGELOG.md
  • Example
  • Installing
  • Versions
  • 91

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.6.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 initialized with an endpoint and cache. If your endpoint requires authentication you can provide it to the client contructor. If you need to change the api token at a later stage, you can call 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() {
  ValueNotifier<Client> client = new ValueNotifier(
    new Client(
      endPoint: 'https://api.github.com/graphql',
      cache: new InMemoryCache(),
      apiToken: '<YOUR_GITHUB_PERSONAL_ACCESS_TOKEN>',
    ),
  );

  ...
}

...

Graphql Provider

In order to use the client, you app needs to be wrapped with the GraphqlProvider widget.

  ...

  return new GraphqlProvider(
    client: client,
    child: new MaterialApp(
      title: 'Flutter Demo',
      ...
    ),
  );

  ...

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 a mutation string:

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

The syntax for mutations is fairly similar to that of a query. The only diffence is that the first argument of the builder function is a mutation function. Just call it to trigger the mutations (Yeah we deliberately 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: 'Star',
    child: new Icon(Icons.star),
  );
},
  onCompleted: (Map<String, dynamic> data) {
    showDialog(
    context: context,
    builder: (BuildContext context) {
      return AlertDialog(
        title: Text('Thanks for your star!'),
        actions: <Widget>[
          SimpleDialogOption(
            child: Text('Dismiss'),
            onPressed: () {
              Navigator.of(context).pop();
            },
          )
        ],
      );
    }
  );
}),

...

Graphql Consumer

You can always access the client direcly from the GraphqlProvider but to make it even easier you can also use the GraphqlConsumer widget.

  ...

  return new GraphqlConsumer(
    builder: (Client client) {
      // do something with the client

      return new Container(
        child: new Text('Hello world'),
      );
    },
  );

  ...

Offline Cache

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

Make sure the CacheProvider widget is inside the GraphqlProvider widget.

...

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new GraphqlProvider(
      client: client,
      child: new CacheProvider(
        child: new MaterialApp(
          title: 'Flutter Demo',
          ...
        ),
      ),
    );
  }
}

...

Roadmap

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

FeatureProgress
Basic queries
Basic mutations
Basic subscriptions🔜
Query variables
Mutation variables
Subscription variables🔜
Query polling
In memory caching
Offline caching
Optimistic results🔜
Client state management🔜

Contributing

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

Contributors

Thanks goes to these wonderful people (emoji key):

<img src="https://avatars2.githubusercontent.com/u/4757453?v=4" width="100px;"/><br /><sub><b>Eustatiu Dima</b></sub><br />🐛 💻 📖 💡 🤔 👀<img src="https://avatars3.githubusercontent.com/u/17142193?v=4" width="100px;"/><br /><sub><b>Zino Hofmann</b></sub><br />🐛 💻 📖 💡 🤔 🚇 👀<img src="https://avatars2.githubusercontent.com/u/15068096?v=4" width="100px;"/><br /><sub><b>Harkirat Saluja</b></sub><br />📖 🤔<img src="https://avatars3.githubusercontent.com/u/5178217?v=4" width="100px;"/><br /><sub><b>Chris Muthig</b></sub><br />💻 📖 💡 🤔<img src="https://avatars1.githubusercontent.com/u/7611406?v=4" width="100px;"/><br /><sub><b>Cal Pratt</b></sub><br />🐛 💻 📖 💡 🤔

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

[0.6.0] - July 19 2018

Breaking change

  • The library now requires your app to be wrapped with the GraphqlProvider widget @HofmannZ
  • The global client variable is no longer available. Instead use the GraphqlConsumer widget

Fixes / Enhancements

  • Added the GraphqlProvider widget. The client is now stored in an InheritedWidget, and can be accessed anywhere within the app.
Client client = GraphqlProvider.of(context).value;
  • Added the GraphqlConsumer widget. For ease of use we added a widget that uses the same builder structure as the Query and Mutation widgets.

Under the hood it access the client from the BuildContext.

  • Added the option to optionally provide the apiToken to the Client constructor. It is still possible to set the apiToken with setter method.
  return new GraphqlConsumer(
    builder: (Client client) {
      // do something with the client

      return new Container();
    },
  );

Docs

  • Added documentation for the new GraphqlProvider
  • Added documentation for the new GraphqlConsumer
  • Changed the setup instructions to include the new widgets
  • Changed the example to include the new widgets

[0.5.4] - July 17 2018

Breaking change

n/a

Fixes / Enhancements

  • Query: changed Timer to Timer.periodic @eusdima
  • Minor logic tweak @eusdima
  • Use absolute paths in the library @HofmannZ

Docs

  • Fix mutations example bug not updating star bool @cal-pratt

[0.5.3] - July 13 2018

Breaking change

n/a

Fixes / Enhancements

  • Added polling timer as a variable for easy deletion on dispose
  • Fixed bug when Query timer is still active when the Query is disposed
  • Added instant query fetch when the query variables are updated

Docs

n/a

[0.5.2] - July 11 2018

Breaking change

n/a

Fixes / Enhancements

  • Fixed error when cache file is non-existent

Docs

n/a

[0.5.1] - June 29 2018

Breaking change

n/a

Fixes / Enhancements

  • Fixed json error parsing.

Docs

n/a

[0.5.0] - June 25 2018

Breaking change

n/a

Fixes / Enhancements

  • Introduced onCompleted callback for mutiations.
  • Excluded some config files from version control.

Docs

  • Fixed typos in the readme.md.
  • The examples inculde an example of the onCompleted callback.

[0.4.1] - June 22 2018

Breaking change

n/a

Fixes / Enhancements

n/a

Docs

  • The examples now porperly reflect the changes to the library.

[0.4.0] - June 21 2018

Breaking change

  • The Client now requires a from of cache.
  • The name of the execute method on the Client class changed to query.

Fixes / Enhancements

  • Implemented in-memory cache.
  • Write memory to file when in background.
  • Added provider widget to save and restore the in-memory cache.
  • Restructure the project.

Docs

  • Update the README.md to refelct changes in the code.
  • update the example to refelct changes in the code.

[0.3.0] - June 16 2018

Breaking change

  • Changed data type to Map instaid of Object to be more explicit.

Fixes / Enhancements

  • Cosmatic changes.

Docs

  • Added a Flutter app example.
  • Fixed the example in README.md.
  • Added more badges.

[0.2.0] - June 15 2018

Breaking change

  • Changed query widget polling argument to pollInterval, following the react-apollo api.

Fixes / Enhancements

  • Query polling is now optional.

Docs

  • Updated the docs with the changes in api.

[0.1.0] - June 15 2018

My colleague and I created a simple implementation of a GraphQL Client for Flutter. (Many thanks to Eus Dima, for his work on the initial client.)

Breaking change

n/a

Fixes / Enhancements

  • A client to connect to your GraphQL server.
  • A query widget to handle GraphQL queries.
  • A mutation widget to handle GraphQL mutations.
  • Simple support for query polling.

Docs

  • Initial documentation.

example/lib/main.dart

import 'package:flutter/material.dart';
import 'package:graphql_flutter/graphql_flutter.dart';

import './queries/readRepositories.dart' as queries;
import './mutations/addStar.dart' as mutations;

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    ValueNotifier<Client> client = new ValueNotifier(
      new Client(
        endPoint: 'https://api.github.com/graphql',
        cache: new InMemoryCache(),
        apiToken: '<YOUR_GITHUB_PERSONAL_ACCESS_TOKEN>',
      ),
    );

    return new GraphqlProvider(
      client: client,
      child: new CacheProvider(
        child: new MaterialApp(
          title: 'Flutter Demo',
          theme: new ThemeData(
            primarySwatch: Colors.blue,
          ),
          home: new MyHomePage(title: 'Flutter Demo Home Page'),
        ),
      ),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({
    Key key,
    this.title,
  }) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text(widget.title),
      ),
      body: new Query(
        queries.readRepositories,
        pollInterval: 1,
        builder: ({
          bool loading,
          Map 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 Mutation(
                mutations.addStar,
                builder: (
                  addStar, {
                  bool loading,
                  Map data,
                  String error,
                }) {
                  if (data.isNotEmpty) {
                    repository['viewerHasStarred'] =
                        data['addStar']['starrable']['viewerHasStarred'];
                  }

                  return new ListTile(
                    leading: repository['viewerHasStarred']
                        ? const Icon(Icons.star, color: Colors.amber)
                        : const Icon(Icons.star_border),
                    title: new Text(repository['name']),
                    // NOTE: optimistic ui updates are not implemented yet, therefore changes may take upto 1 second to show.
                    onTap: () {
                      addStar({
                        'starrableId': repository['id'],
                      });
                    },
                  );
                },
                onCompleted: (Map<String, dynamic> data) {
                  showDialog(
                    context: context,
                    builder: (BuildContext context) {
                      return AlertDialog(
                        title: Text('Thanks for your star!'),
                        actions: <Widget>[
                          SimpleDialogOption(
                            child: Text('Dismiss'),
                            onPressed: () {
                              Navigator.of(context).pop();
                            },
                          )
                        ],
                      );
                    },
                  );
                },
              );
            },
          );
        },
      ),
    );
  }
}

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  graphql_flutter: ^0.6.0

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter packages get

Alternatively, your editor might support flutter packages get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:graphql_flutter/graphql_flutter.dart';
  
Version Uploaded Documentation Archive
0.6.0 Jul 20, 2018 Go to the documentation of graphql_flutter 0.6.0 Download graphql_flutter 0.6.0 archive
0.5.4 Jul 17, 2018 Go to the documentation of graphql_flutter 0.5.4 Download graphql_flutter 0.5.4 archive
0.5.3 Jul 13, 2018 Go to the documentation of graphql_flutter 0.5.3 Download graphql_flutter 0.5.3 archive
0.5.2 Jul 11, 2018 Go to the documentation of graphql_flutter 0.5.2 Download graphql_flutter 0.5.2 archive
0.5.1 Jun 29, 2018 Go to the documentation of graphql_flutter 0.5.1 Download graphql_flutter 0.5.1 archive
0.5.0 Jun 25, 2018 Go to the documentation of graphql_flutter 0.5.0 Download graphql_flutter 0.5.0 archive
0.4.1 Jun 22, 2018 Go to the documentation of graphql_flutter 0.4.1 Download graphql_flutter 0.4.1 archive
0.4.0 Jun 22, 2018 Go to the documentation of graphql_flutter 0.4.0 Download graphql_flutter 0.4.0 archive
0.3.0 Jun 16, 2018 Go to the documentation of graphql_flutter 0.3.0 Download graphql_flutter 0.3.0 archive
0.2.0 Jun 15, 2018 Go to the documentation of graphql_flutter 0.2.0 Download graphql_flutter 0.2.0 archive

All 11 versions...

Popularity:
Describes how popular the package is relative to other packages. [more]
83
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100
Overall:
Weighted score of the above. [more]
91
Learn more about scoring.

We analyzed this package on Jul 20, 2018, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.0.0-dev.69.0
  • pana: 0.11.7
  • Flutter: 0.5.5

Platforms

Detected platforms: Flutter

References Flutter, and has no conflicting libraries.

Suggestions

The description is too short.

Add more detail about the package, what it does and what is its target use case. Try to write at least 60 characters.

Package is pre-v1 release.

While there is nothing inherently wrong with versions of 0.*.*, it usually means that the author is still experimenting with the general direction of the API.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.0.0-dev.52.0
flutter 0.0.0
http ^0.11.0 0.11.3+17
path_provider ^0.4.0 0.4.1
test ^0.12.0 0.12.42 1.3.0
Transitive dependencies
analyzer 0.32.3
args 1.4.4
async 2.0.8
boolean_selector 1.0.4
charcode 1.1.2
collection 1.14.6 1.14.11
convert 2.0.2
crypto 2.0.6
csslib 0.14.4+1
front_end 0.1.3
glob 1.1.7
html 0.13.3+2
http_multi_server 2.0.5
http_parser 3.1.3
io 0.3.3
js 0.6.1+1
json_rpc_2 2.0.8
kernel 0.3.3
logging 0.11.3+2
matcher 0.12.3+1 0.12.4
meta 1.1.5 1.1.6
mime 0.9.6+1
multi_server_socket 1.0.2
node_preamble 1.4.3
package_config 1.0.5
package_resolver 1.0.3
path 1.6.2
plugin 0.2.0+3
pool 1.3.5
pub_semver 1.4.2
shelf 0.7.3+3
shelf_packages_handler 1.0.4
shelf_static 0.2.8
shelf_web_socket 0.2.2+3
sky_engine 0.0.99
source_map_stack_trace 1.1.5
source_maps 0.10.7
source_span 1.4.1
stack_trace 1.9.3
stream_channel 1.6.8
string_scanner 1.0.3
term_glyph 1.0.1
typed_data 1.1.5 1.1.6
utf 0.9.0+5
vector_math 2.0.6 2.0.7
vm_service_client 0.2.5
watcher 0.9.7+10
web_socket_channel 1.0.9
yaml 2.1.15
Dev dependencies
flutter_test