Codementor Events

How to GraphQL with Flutter?

Published Jun 16, 2019Last updated Dec 12, 2019

GraphQL Rsources:
https://graphql.org/
https://www.howtographql.com

GraphQL is developed to cope with the need for more flexibility and efficiency! It solves many of the shortcomings and inefficiencies that developers experience when interacting with REST APIs.

GraphQL over REST, Why?

Over fetching: Over-fetching is fetching too much data, aka there is data in the response you don't use.

Under fetching: Under-fetching is not having enough data with a call to an endpoint, leading you to call the second endpoint. In both cases, they are performances issues: you either use more bandwidth than you should, or you are making more HTTP requests that you should.

GraphQL-Flutter

Let's use GraphQL in flutter with example:
We are going to fetch and display list of countries with name, currency and flag emoji using https://countries.trevorblades.com/

  1. Add this dependency to install GraphQL-Flutter library.
    https://pub.dev/packages/graphql_flutter
dependencies:
  graphql_flutter: ^1.0.0
  1. main.dart of your flutter app:
import 'package:flutter/material.dart';
import 'package:graphql_demo/country_list.dart';
import 'package:graphql_flutter/graphql_flutter.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
  	/// HttpLink - A system of modular components for GraphQL networking.
    final HttpLink httpLink =
        HttpLink(uri: 'https://countries.trevorblades.com/');
  
    final ValueNotifier<GraphQLClient> client = ValueNotifier<GraphQLClient>(
      GraphQLClient(
        link: httpLink as Link,
        cache: OptimisticCache(
          dataIdFromObject: typenameDataIdFromObject,
        ),
      ),
    );

    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: GraphQLProvider(
        child: CountryListView(),
        client: client,
      ),
    );
  }
}
  1. country_list.dart
import 'package:flutter/material.dart';
import 'package:graphql_flutter/graphql_flutter.dart';

class CountryListView extends StatelessWidget {
  final String query = '''
                      query ReadCountries {
                          countries {
                            code
                            name
                            currency
                            emoji
                          }
                      }
                  ''';
                  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('List of Countries'),
      ),
      body: Query(
        options: QueryOptions(document: query),
        builder: (QueryResult result, {VoidCallback refetch}) {
          if (result.loading) {
            return Center(child: CircularProgressIndicator());
          }

          if (result.data == null) {
            return Center(child: Text('Countries not found.'));
          }

          return _countriesView(result);
        },
      ),
    );
  }
  
  ListView _countriesView(QueryResult result) {
    final countryList = result.data['countries'];
    return ListView.separated(
      itemCount: countryList.length,
      itemBuilder: (context, index) {
        return ListTile(
          title: Text(countryList[index]['name']),
          subtitle: Text('Currency: ${countryList[index]['currency']}'),
          leading: Text(countryList[index]['emoji']),
          onTap: () {
            final snackBar = SnackBar(
                content:
                    Text('Selected Country: ${countryList[index]['name']}'));
            Scaffold.of(context).showSnackBar(snackBar);
          },
        );
      },
      separatorBuilder: (context, index) {
        return Divider();
      },
    );
  }
}

country-list.png

That's it, enjoy ๐Ÿ˜ƒ

Discover and read more posts from Sunil Mishra
get started