Flutter

Flutter GraphQL Setup

Introduction

In the last tutorial we understood the benefits of using Back4app GraphQL with Flutter. In this article we are going to setup the basic scaffold for the project and connect to the Back4app Server

Goals

  • Setup the Flutter Environment
  • Flutter GraphQL setup anatomy
  • Flutter GraphQL connection
  • Flutter GraphQL connection reuse and patterns

Prerequisites

  • We require that the user has some basic understanding of Dart and Flutter.
  • Though not necessary, GraphQL cookbook will be useful in understanding some of the GraphQL concepts.

Step 0: Setup the App from Back4app Hub

We would need to create an app, you can follow documentation on: https://www.back4app.com/docs/get-started/new-parse-app

We would be using Back4app Hub to set up necessary classes for this tutorial.
Please go to: https://www.back4app.com/database/chinmay/flutter-graphql. Click on connect to API.

Select the newly created app and then you are done!

Step 1: Setting up Flutter

Setting up flutter is relatively painless. We will follow the setup instructions at the official flutter website.
After this we will create a simple flutter application using the command:

1
flutter create flutter_graphql_setup

Check if everything is OK using the command flutter doctor, by Running the application:

1
2
cd flutter_graphql_setup 
flutter run

Step 2: Installing the Flutter GraphQL library

For implementing this client we are going to use the flutter_graphql library as mentioned in the first article.
We will now add adding this to your packages pubspec.yaml.

1
2
dependencies:
graphql_flutter: ^3.0.0

Step 3: Create a Flutter GraphQL Provider

In GraphQL we do not have to work with multiple endpoints, we only have a single endpoint that is used to query the request data. And we send GraphQL queries to that endpoint. So generally what we do is that we create an instance of the client that is responsible for sending the appropriate headers and format the queries as per our need.
We will be creating a client, for this we need a link (instance of the HttpLink class) and a cache store. We will be using HttpLink as our link and OptimisticCache for our caching. Code would be written in the following manner:

In the main.dart we will write the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
final HttpLink httpLink = HttpLink(
      uri: 'https://parseapi.back4app.com/graphql',
      headers: {
        'X-Parse-Application-Id': kParseApplicationId,
        'X-Parse-Client-Key': kParseClientKey,
      }, //getheaders()
    );

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

Step 4: Connect to Back4app using the GraphQL

Go to the Back4app Dashboard in the option “API Console” > “GraphQl Console”:

Note down:

  1. API url
  2. Parse App ID
  3. Parse Client ID

We will create a new file constants.dart in lib folder of our project.

1
2
String kParseApplicationId= "";
String kParseClientKey = "";

Step 5: Querying Data

Our component will be wrapped by the GraphQLProvider widget, which would provide necessary details for the widget.
We will need to provide an instance of client that we created in step 2.
We will use GraphQL console, to write our query. You can learn more about GraphQL queries in our GraphQL cookbook section.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import 'package:graphql_flutter/graphql_flutter.dart';
import 'constants.dart';

class _MyHomePageState extends State<MyHomePage> {
  String name;
  String saveFormat;
  String objectId;

  String query = '''
  query FindLanguages{
  languages{
    count,
    edges{
      node{
        name,
        saveFormat
      }
    }
  }
}
  ''';

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        appBar: AppBar(
          title: Text(
            'Parsing data using GraphQL',
          ),
        ),
        body: Query(
          options: QueryOptions(
            documentNode: gql(query),
          ),
          builder: (
            QueryResult result, {
            Refetch refetch,
            FetchMore fetchMore,
          }) {
            if (result.data == null) { //check if data is loading
              return Center(
                  child: Text(
                "Loading...",
                style: TextStyle(fontSize: 20.0),
              ));
            }  
             //to implement rendering logic
          },
        ),
      ),
    );
  }
}

Step 6: Render the list

We will use the ListView widget to render the list, in the main.dart

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
else {
              return ListView.builder(
                itemBuilder: (BuildContext context, int index) {
                  return ListTile(
                    title: Text(result.data["programmingLanguages"]["edges"][index]["node"]['name']),
                    trailing: Text(
                      result.data["programmingLanguages"]["edges"][index]
                        ["node"]['stronglyTyped'] ? "Strongly Typed":"Weekly Typed"
                    ),
                  );
                },
                itemCount: result.data["programmingLanguages"]["edges"].length,
              );
            }

We should get the following on our screen:

Conclusion

We have configured the Flutter GraphQL client and connect to the Back4app GraphQL api.
You can find the code for the same here: https://github.com/templates-back4app/Flutter-GraphQL/tree/flutter-graphql-setup.