Flutter x GraphQL
DUBV
follow
On July 1
– 4 minutes to read
As a front-end developer, I have been working on many projects using REST apis for a long time, and I have noticed some inefficiencies when interacting with REST.
- There are many endpoints in the source code that I need to deal with.
- Even if I only want to display one field in my user interface, the server may provide me with more data than I need.
- It takes a lot of time to communicate with the back-end team to clarify the API files.
- The structure of the request object (the front end aspect) must depend on the server aspect.
Have you ever wasted a lot of time because of the above reasons? Well, if your answer is “yes,” then GraphQL will save you time.
So what exactly is GraphQL?
GraphQL is a query language and application programming interface (API) server-side runtime that prioritises giving customers the data they ask for, not more.
GraphQL aims to make the API fast, flexible, and developer-friendly. It can even be deployed in an integrated development environment (IDE) called GraphiQL. As an alternative to REST, GraphQL lets developers build requests to extract data from multiple data sources in a single API call.
When you read the above definition, I’m sure you’ll think of SQL (Structured Query Language) and recall the “legendary” terms of your freshman year, such as SELECT, INSERT, UPDATE, DELETE, and WHERE.
Later, this definition reminds you of REST, and I’m sure you’ll come up with another legendary term. C.R.U.D., right?
Now, what if we got something that combined all of these legendary buzzwords? Yes, the Man who saved my Time was born **–GraphQL. 支那
In the scope of this article, we’ll introduce the basic concepts of GraphQL from the front end.
GraphQL operation
There are three main types of GraphQL operations. Query, mutate, subscribe.
Let’s assume that we have a model ticket in our schema that contains three fields. id, status, created_at
Query (a read-only fetch
1. Retrieve multiple entries
2. Get a single entry
Change (fetch after modification).
1. Add an item
2. Update an entry
3. Delete an entry
Subscribe (a query of real-time data
Now, let’s apply it to Flutter
First, in order to use GraphQL, you need a server library (unless you have a solid back-end team). There are many supported server libraries, but I heartily recommend using GraphCMS.
Second, in order for your Flutter project to be able to use GraphQL, you need a GraphQL client to communicate with the server. There are some great libraries on pub.dev, such as this Graphql_flutter and this ferry.
Coding time!
All of the following scripts and related stuff can be found in the REPo: Fluttour). Before you start, take a look at README.
Here’s what we’re going to do.
- Create a basic GraphQLAPIClient.
- Create an asynchronous function that contains the _ mutation/query/subscribe file that we want to execute in the class extending GraphQLAPIClient. The exception is then handled and the data is parsed from the response.
- Create another asynchronous function in our provider class that extends from ChangeNotifier to call the function of Step 2 and begin data processing.
- Notifies the listener that data from the server may have changed.
Create a basic GraphQLAPIClient
> api_client.dart
Copy the code
Here, we create a private **_client** function that returns a GraphQLClient constructor
- The cache. The initial cache to be used in the data store.
- Link. The GraphQL file will be parsed into a link in response. In this case, we’re using HttpLink, and we’re going to attach it with AuthLink to attach our GraphCMS public tag.
- DefaultPolicies. Default policy set for each client action.
After that, we create a query function to execute our query.
Future<QueryResult> query(String queries) async { final WatchQueryOptions _options = WatchQueryOptions( document: gql(queries), pollInterval: Duration(seconds: 15), fetchResults: true, ); return await _client().query(_options); }Copy the code
Now we create a mutation function and send the mutation results to the server.
Future<QueryResult> mutation(String queries) async { final MutationOptions _options = MutationOptions( document: gql(queries), ); return await _client().mutate(_options); }Copy the code
Pretty cool, huh?
Create a request
In an extension from GraphQLAPIClient class, we create a request function, will mutate/query/subscription to the server.
Future<T> get() async { String your_query= """ query { /// write your query } """;
Copy the code
For mutations, all you have to do is change this.query to this.mutation
Do data processing/notification listeners in your provider class
Future<void> get() async { final result = await this._request.get(); if (result ! = null) { } else { } // handle data & notify the listeners here. // there are a bunch of ways to notify the listeners, // in this example, I'm using the delegation pattern and // notifyListeners function.Copy the code
trap
1. In order to run this project, you need to run it in a specific environment.
- Development.
flutter run -t lib/main_dev.dart
- Production environment.
flutter run -t lib/main_prod.dart
2. You need a personal access token to validate the GraphCMS server. To get one, go to graphcms.com/docs/author… .
If you don’t want to waste your time, you can use my token, which can be found in this REPo.
Finally, enjoy your work and see how incredible GraphQL is.
This is my first post and I hope it will be useful to those new to GraphQL and Flutter. 🍻