DEV Community

Cover image for GraphQL with Flutter
Nitish Kumar Singh
Nitish Kumar Singh

Posted on • Originally published at Medium on

GraphQL with Flutter

GraphQL is a query language in which we send the query to the GraphQL Server. The server executes the query at runtime for fulfilling those queries with your existing data.

Let’s me make you understand this in more easy words. I suppose that you know SQL (Structured Query Language). If we are having a user table with the information about their name, age, email, phone. Now you want to fetch the name and email of the user then you will write a query for that and you will get that information. (Select name, email form the users).

You will not get age and phone of the user because you have not asked for that information. These are a thing of the server-side (backend). If you are a frontend developer and you had made 20 pages where you need users information. You will ask the backend developer that I want user information on different pages so I need an API. Backend developer will make API will give you an endpoint.

> on 6 pages you want user’s name only

> on 10 pages you want user’s email and name

> on 4 pages you want user’s name email and phone.

So you backend developer may apply two approaches.

  1. He will make 3 different endpoints with different data.
  2. He can make a common API with all the information.

What is the problem with these two approaches?

  1. We are having multiple endpoints. If someday we will ned user’s name and age then we need to make another endpoint.
  2. We are not having multiple endpoints but We are over fetching the data, on each page we don’t want the user’s phone still we are getting the data.

You might think that there is nothing bad with over fetching because extra data will not be going to kill our bandwidth. You are probably wrong here because you are thinking on a low scale. You have not seen the large API’s.

I know you came here to Read about the Flutter

but one last Demo about GraphQL then we will move to Flutter part

Demo from GraphQL official website

There is various implementation for the GraphQL for different Technologies. First, we need to implement the GraphQL on to our server then we ask for data from that server using GraphQL Query. So in a flutter, we don’t need to implement the GraphQL server. We will use a readymade GraphQL serverfrom where we will fetch the data.

GraphQL Playground

Let’s come to Flutter coding part and understand how exactly it works.

Graphql Flutter is 1.x.x is currently available on the flutter dev channel. If you don’t know what is this dev channel and how to channel to the dev channel then don’t worry I’ll tell you.

Flutter is having 4 channel where flutter (beta, dev, master stable). by default, we all are on the stable channel and in order to use GraphQL (1.x.x). we need to change the channel.

How to change the channel?

$ flutter channel dev

Now you need to check the channel and this will download some Dart never version on which flutter dev channel is dependent. You just need to check the channel and that file will automatically get downloaded.

$ flutter channel

Flutter start’s from here

First, we need to add the dependency for the GraphQL (graphql_flutter)

name: flutter_graphql_demo
description: A new Flutter application.
version: 1.0.0+1

environment:
  sdk: ">=2.1.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter
  cupertino_icons: ^0.1.2
  graphql_flutter: ^1.0.0+4

Now Let’s start the writing code for the flutter. First, we create a GraphQL Client and that client will talk to the GraphQL server we just to notify the client about the GraphQL Query.

Let’s set up the GraphQL Client

import 'package:flutter/material.dart';
import 'package:graphql_flutter/graphql_flutter.dart';

void main() {
  runApp(MaterialApp(title: "GQL App",home: MyApp()));
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    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 GraphQLProvider(
      child: HomePage(),
      client: client,
    );
  }
}

I will talk about each of the points which is related to GraphQL in the Flutter.

To use the client it first needs to be initialized with a link and cache. For this example, we will be using an HttpLink as our link and Optimisticache as our cache.

In line number 15 you can see the link. Link is used for pointing to the endpoint of GraphQL server with the required header (if any). The header is used to authenticate the client.

ValueNotifiernotified to their listener whenever there is any value change

We are wrapping our complete page of the application with GraphQLProvider. So, that we can make a request to the GraphQL server without specifying the endpoint and the header. This means from the inside of our page we just need to tell the query and GraphQL provider will do all the tasks for us. That’s why it is known and Client Libray.

Here we had separated the GraphQL client in a different stateless client we had not written any UI code here because I want to keep them separate (GraphQL Client and Flutter UI).

This is the Query which we will send to get GraphQL server and display the list of Countries. You can try this query by copying and pasting it to this GraphQL Server.

query {
 countries {
 name
 }
}

Let’s consume reponse of GraphQL Clinet

Now we are going to make the UI for our application

class HomePage extends StatelessWidget {
  String query = r"""
                      query GetCountries{
                          countries {
                            name
                          }
                      }
                  """;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("GraphlQL Client"),
      ),
      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("No Data Found !"));
          }
          return ListView.builder(
            itemBuilder: (BuildContext context, int index) {
              return ListTile(
                title: Text(result.data['countries'][index]['name'])
              );
            },
            itemCount: result.data['countries'].length,
          );
        },
      ),
    );
  }
}

This is Code for our UI and Let’s understand the GraphQL part out this code.

We are using Query() widget which is defined by the plugin. It is not a native widget. The Query has two fields here

  1. options: Options ask for the query. What query we want to send to the server and if you want to some variable along with query then we have to pass that from the options.
  2. builder: builder is the same as other builders in a flutter. Builder changes its state based on the data. (You can compare this builder as FutureBuilder.

First, it will send the query to the server and will go to the loading state. you can see the while loading we are showing the CircularProgressBar(). Once the query the executed and loading state gets changed it will come to the completed state.

In the completed state either it will have an error or it will have the data. If it is not having data then we are showing a message that is not data found!.

result.data = the data which you have seen in the GraphQL Playground.

If we get the data then we are showing the response. The response the same as JSON response you just need to grab the countries out of it and show in your UI. I assume that you know this.

nitishk72/flutter_graphql_demo

Thanks for reading if you like then do clap. If you have anything to say then do comment don’t be alien.

Nitish Kumar Singh🇮🇳 (@nitishk72_) | Twitter


Top comments (0)