A simple list with GraphQL calls using BLOC architecture.

Reading time: 2 minutes

You will find this post connected to ‘A simple list with GraphQL calls using BLOC architecture’. I won’t share similar code here, just keep in mind that we are using the same Country ‘model’ class, CountriesBloc with the same events and states, and even the same example StatelessWidget that creates and holds CountriesBloc.

The only difference here is the CountriesRepository class. It’s good practice in general to have an abstract class for repositories that don’t depend on call implementations itself.

We’ll use next one more additional package, don’t forget to ‘get’ it:

dependencies:
	graphql_flutter: ^3.1.0

And of course new CountriesRepository :

import 'package:graphql_flutter/graphql_flutter.dart';

import 'country.dart';

class CountriesRepository {
  final String call = "query{countries{name capital}}";
  final GraphQLClient _client = graphQlClient();

  Future<List<Country>> fetchCountries() async {
    final WatchQueryOptions _options = WatchQueryOptions(
      documentNode: gql(call),
      variables: <String, dynamic>{},
    );
    return _client
        .query(_options)
        .then((value) => (value.data["countries"] as List<dynamic>).map((e) => Country.fromJson(e)).toList());
  }
}

GraphQLClient graphQlClient() {
  final HttpLink _httpLink = HttpLink(
    uri: 'https://countries.trevorblades.com/',
  );

  return GraphQLClient(
    cache: InMemoryCache(),
    link: _httpLink,
  );
}

To create GraphQLClient we provide InMemoryCache(). We won’t go deep about how to choose the correct one, as it depends on a lot of factors, InMemoryCache is fine for this example. The second parameter in HttpLink builds from Uri ‘https://countries.trevorblades.com/‘, free to use GraphQL API.

To query for the result we pass variables (empty map) and documentNode created from field ‘call’, where we describe that we want to query all countries and return fields name and capital. Here is more about how to make calls. The response of _client.query(_options) is Future, so we call then to work with the result.

That’s how response looks like:

{
  "data": {
    "countries": [
      {
        "name": "Andorra",
        "capital": "Andorra la Vella"
      }
      ...
    ]
}

No need to parse with ‘dart:convert’, ‘data’ is parent node and it’s List<dynamic> or Map<dynamic>.

And we will see same result as in REST case:

Leave a Reply

Your email address will not be published. Required fields are marked *