First depend on the library by adding this to your packages pubspec.yaml
:
dependencies:
graphql_flutter: ^0.3.0
Now inside your Dart code you can import it.
import 'package:graphql_flutter/graphql_flutter.dart';
To use the client it first needs to be initialzed with an endpoint. 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('https://api.github.com/graphql');
client.apiToken = '<YOUR_GITHUB_PERSONAL_ACCESS_TOKEN>';
...
}
...
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']);
});
},
);
...
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),
);
}),
...
Feel free to open a PR with any suggetions! We'll be actively working on the library ourselfs.
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!