Both GraphQL tools and Flutter introduced a new style of software development when they were first released. Apito's GraphQL tools and database API enable developers to fetch data in their desired shape and format from our instant API builder. Flutter made it possible to build mobile apps that seamlessly integrate with our build API tool using one language and cross-compile for other platforms.
First, depend on this package:
dependencies:
graphql_flutter: ^4.0.0-beta
And then import it inside your dart code:
import 'package:graphql_flutter/graphql_flutter.dart';
Find the migration from version 3 to version 4 here.
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. 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 GraphQLCache.
Tip:
Always remember to replace
API_SECRET
in the Bearer Token andproject-id
in the URL with the correct values from the Apito console.
If you are unsure where to find your API secrets and endpoints for your project, visit this page.
import 'package:graphql_flutter/graphql_flutter.dart';
void main() async {
// We're using HiveStore for persistence,
// so we need to initialize Hive.
await initHiveForFlutter();
final HttpLink httpLink = HttpLink(
'https://api.apito.io/secured/graphql',
);
final AuthLink authLink = AuthLink(
getToken: () async => 'Bearer API_SECRET',
// OR
// getToken: () => 'Bearer <YOUR_PERSONAL_ACCESS_TOKEN>',
);
final Link link = authLink.concat(httpLink);
ValueNotifier<GraphQLClient> client = ValueNotifier(
GraphQLClient(
link: link,
// The default store is the InMemoryStore, which does NOT persist to disk
store: GraphQLCache(store: HiveStore()),
),
);
}
In order to use the client, your Query
and Mutation
widgets must be wrapped with the GraphQLProvider
widget.
We recommend wrapping your MaterialApp with the GraphQLProvider widget.
...
return GraphQLProvider(
client: client,
child: MaterialApp(
title: 'Flutter Demo',
...
),
);
...
Creating a query is as simple as creating a multiline string:
String readRepositories = """
query ReadRepositories(\$nRepositories: Int!) {
viewer {
repositories(last: \$nRepositories) {
nodes {
id
name
viewerHasStarred
}
}
}
}
""";
In your widget:
// ...
Query(
options: QueryOptions(
document: gql(readRepositories), // this is the query string you just created
variables: {
'nRepositories': 50,
},
pollInterval: Duration(seconds: 10),
),
// Just like in apollo refetch() could be used to manually trigger a refetch
// while fetchMore() can be used for pagination purpose
builder: (QueryResult result, { VoidCallback refetch, FetchMore fetchMore }) {
if (result.hasException) {
return Text(result.exception.toString());
}
if (result.isLoading) {
return Text('Loading');
}
// it can be either Map or List
List repositories = result.data['viewer']['repositories']['nodes'];
return ListView.builder(
itemCount: repositories.length,
itemBuilder: (context, index) {
final repository = repositories[index];
return Text(repository['name']);
});
},
);
// ...
Again first create a mutation string:
String addStar = """
mutation AddStar(\$starrableId: ID!) {
addStar(input: {starrableId: \$starrableId}) {
starrable {
viewerHasStarred
}
}
}
""";
The syntax for mutations is fairly similar to that of a query. The only difference 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.)
...
Mutation(
options: MutationOptions(
document: gql(addStar), // this is the mutation string you just created
// you can update the cache based on results
update: (GraphQLDataProxy cache, QueryResult result) {
return cache;
},
// or do something with the result.data on completion
onCompleted: (dynamic resultData) {
print(resultData);
},
),
builder: (
RunMutation runMutation,
QueryResult result,
) {
return FloatingActionButton(
onPressed: () => runMutation({
'starrableId': <A_STARTABLE_REPOSITORY_ID>,
}),
tooltip: 'Star',
child: Icon(Icons.star),
);
},
);
...
For more detailed guide be sure to check out the official guide of the graphql_flutter
page here