First, depend on this package:
dependencies:
graphql: ^3.0.0
And then import it inside your dart code:
import 'package:graphql/client.dart';
Find the migration from version 2 to version 3 here.
To parse documents at build-time use ast_builder
from
package:gql_code_gen
:
dev_dependencies:
gql_code_gen: ^0.1.0
To connect to a GraphQL Server, we first need to create a GraphQLClient
. A GraphQLClient
requires both a cache
and a link
to be initialized.
In our example below, we will be using the Github Public API. In our example below, we are going to use HttpLink
which we will concatenate with AuthLink
so as to attach our github access token. For the cache, we are going to use InMemoryCache
.
// ...
final HttpLink _httpLink = HttpLink(
uri: 'https://api.github.com/graphql',
);
final AuthLink _authLink = AuthLink(
getToken: () async => 'Bearer $YOUR_PERSONAL_ACCESS_TOKEN',
);
final Link _link = _authLink.concat(_httpLink);
final GraphQLClient _client = GraphQLClient(
cache: InMemoryCache(),
link: _link,
);
// ...
final Link _link = _authLink.concat(_httpLink);
Link.from
joins multiple links into a single link at once.
final Link _link = Link.from([_authLink, _httpLink]);
Once you have initialized a client, you can run queries and mutations.
Creating a query is as simple as creating a multiline string:
const String readRepositories = r'''
query ReadRepositories($nRepositories: Int!) {
viewer {
repositories(last: $nRepositories) {
nodes {
__typename
id
name
viewerHasStarred
}
}
}
}
''';
Then create a QueryOptions
object:
NB: for
document
- Use our built-in help function -gql(query)
to convert your document string to ASTsdocument
.
In our case, we need to pass nRepositories
variable and the document name is readRepositories
.
const int nRepositories = 50;
final QueryOptions options = QueryOptions(
document: gql(readRepositories),
variables: <String, dynamic>{
'nRepositories': nRepositories,
},
);
And finally you can send the query to the server and await
the response:
// ...
final QueryResult result = await _client.query(options);
if (result.hasException) {
print(result.exception.toString());
}
final List<dynamic> repositories =
result.data['viewer']['repositories']['nodes'] as List<dynamic>;
// ...
Creating a Mutation is also similar to creating a query, with a small difference. First, start with a multiline string:
const String addStar = r'''
mutation AddStar($starrableId: ID!) {
action: addStar(input: {starrableId: $starrableId}) {
starrable {
viewerHasStarred
}
}
}
''';
Then instead of the QueryOptions
, for mutations we will MutationOptions
, which is where we pass our mutation and id of the repository we are starring.
// ...
final MutationOptions options = MutationOptions(
document: gql(addStar),
variables: <String, dynamic>{
'starrableId': repositoryID,
},
);
// ...
And finally you can send the query to the server and await
the response:
// ...
final QueryResult result = await _client.mutate(options);
if (result.hasException) {
print(result.exception.toString());
return
}
final bool isStarred =
result.data['action']['starrable']['viewerHasStarred'] as bool;
if (isStarred) {
print('Thanks for your star!');
return;
}
// ...
We are deprecating
document
and recommend you update your application to usedocument
instead.document
will be removed from the api in a future version.
For example:
// ...
final MutationOptions options = MutationOptions(
document: gql(addStar),
variables: <String, dynamic>{
'starrableId': repositoryID,
},
);
// ...
With package:gql_code_gen
you can parse your *.graphql
files at build-time.
add_star.graphql
:
mutation AddStar($starrableId: ID!) {
action: addStar(input: {starrableId: $starrableId}) {
starrable {
viewerHasStarred
}
}
}
import 'package:gql/add_star.ast.g.dart' as add_star;
// ...
final MutationOptions options = MutationOptions(
document: add_star.document,
variables: <String, dynamic>{
'starrableId': repositoryID,
},
);
// ...
Perform custom logic when a GraphQL or network error happens, such as logging or signing out.
final ErrorLink errorLink = ErrorLink(errorHandler: (ErrorResponse response) {
Operation operation = response.operation;
FetchResult result = response.fetchResult;
OperationException exception = response.exception;
print(exception.toString());
});