GraphQL Flutter API Example

In this article, we are going to learn how to use GraphQL flutter package to execute queries on the server. In this flutter example, we will create queries to fetch countries data from API.

GraphQL is query language that allows us to send query to GraphQL server. Then server gives filtered data to us from existing data according to our queries.

For example one api contains user data such as id, first name, last name, address etc. But we want only first name of the user not the whole user info in the data response then this will be possible with GraphQL API.

Using GraphQL API, we can retrieve data according to our requirement. We do not need to ask backend developer to contain only particular data. First we need to create GraphQLClient to connect to GraphQL server.

 

Add required dependency in your pubspec.yaml file

graphql_flutter: ^3.0.0
 
 

Connect GraphQL Flutter Server

First we need to initialize GraphQLClient with link and cache to use it. Here we are using HttpLink as our link and Optimisticache as our cache. HttpLink is used to retrieve endpoint of GraphQL server. ValueNotifier is used to notify GraphQLClient if any value is changed.

GraphQLProvider is used to connect GraphQL server without any endpoint of GraphQL server. We just need to wrap all widgets under the GraphQLProvider and add our GraphQLClient to client property.

final HttpLink httpLink = HttpLink(uri: ‘https://countries.trevorblades.com/’);

final ValueNotifier<GraphQLClient> client = ValueNotifier<GraphQLClient>(
GraphQLClient(
    link: httpLink as Link,
    cache: OptimisticCache(
        dataIdFromObject: typenameDataIdFromObject,
    ),
),
);

 
 

Create Query for GraphQL Flutter

final String query = ”’
query ReadCountries {
countries {
name
currency
}
}
”’;
 
 

Display API Data

GraphQLProvider(
child: Query(
options: QueryOptions(document: query),
builder: (QueryResult result,
{VoidCallback refetch, FetchMore fetchMore}) {
if (result.loading) {
    return Center(child: CircularProgressIndicator());
}

if (result.data == null) {
    return Center(child: Text(‘Data not found.’));
}

final listCountries = result.data[‘countries’];

return ListView.separated(
itemBuilder: (context, index) {
return Container(
padding: EdgeInsets.all(10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
    listCountries[index][‘name’]??”,
    style: TextStyle(fontWeight: FontWeight.bold, fontSize: 22),
),
SizedBox(height: 5),
Text(listCountries[index][‘currency’]??”),
SizedBox(height: 5),
],
),
);
},
separatorBuilder: (context, index) {
    return Divider();
},
itemCount: listCountries.length);
},
),
client: client,
),

 
graphql flutter
 

Leave a Reply