What is GraphQL & using it on Flutter
In time you will know what it’s like to lose

What is GraphQL & using it on Flutter

The hardest choices require the strongest will

We all have worked by consuming REST APIs from day one of our development but as data queries are getting more complex with data growing larger it is turning to be expensive with respect to time and computations. There was requirement of framework or a layer which could make the appropriate optimisation in querying and consuming APIs. Then comes GraphQL:

Let’s talk about this plan of yours. I think it’s good, except it sucks. So let me do the plan and that way it might be really good

What is GraphQL?

GraphQL is a query language for the APIs for getting your data. It is an alternative for the REST APIs. It is not specific for a single platform and works for all type of clients including Android, iOS or web. It stands between your server and client and helps you to query your data in a more optimised way. Lets see why:

Main Advantages:

  • Client driven, You only get what you need: This means that clients define what type of response they are interested to get in return which provides more control powers to the client on server. For example if the query is:
Query:
query {
  repository(owner:"chirag", name:"JadavChirag") {
    name
    description
    url
  }
}
Response:
{
  "data": {
    "repository": {
      "name": "react-native-GPay",
      "description": "Payment gateway npm lib for react native.",
      "forkCount": 3,
      "url": "https://github.com/JadavChirag/react-native-GPay"
    }
  }
}

In this example the client query requests the name, description, fork count and URL of the respective repository and thus in response we only get only those fields which were requested which will reduce our parse time comparatively from the case in which we will get much detailed JSON response.

  • Avoid doing multiple calls : In case of REST APIs we have to maintain multiple endpoints. For instance, one end point for getting the “id” of user from /users and details of user from /users/<id> which will cost us two calls for the details. Now from the graphQL implementation this will reduce to single query because of the concept of Arguments in GraphQL
Resultant single Query:

query{
User(id:"radhe12321"){ //Argument
   name        
   subject           
 }
}
No alt text provided for this image

Important tools and APIs to know before using:

So, you must be thinking that this is OK but I need some already developed graphQL APIs for practising the working on a client side (if you are a client side developer) and other important tools. So, here is an important list you can bookmark:

PS: If you already have a REST API and want to shift to graphQL API you can use  express-graphql  which will make a graphQL wrapper around your
REST API or a SOAP and then you can use it as a graphQL API.

Important tools:

  • GraphiQL: This is a type of plugin in your browser which is used to test your queries on the APIs. You can customise your requests by adding URLs and adding on different header types. Link: https://github.com/graphql/graphiql
  • Altair GraphQL Client: It is a type of postman for graphQL APIs which is also available as Mozilla Firefox add-on to test the queries. Link: https://github.com/imolorhe/altair
Starting Up GraphQL on Flutter

Without wasting an inch of time, let me start by integrating Graph QL and Flutter….

First things first, install the plugin named :

graphql_flutter 

in the pubspec.yaml. Now, import

importpackage:graphql_flutter/graphql_flutter.dart’;

Basically, in terms of GraphQL terminology,

  1. Query : means we need to fetch the data, for instance get requests.
  2. Mutation : means we need to update/insert the data, for instance post/put/delete requests.

In order to call the Graph QL requests, we need to use

import 'package:flutter/material.dart';
	import 'package:scalable_image/scalable_image.dart';
	import 'dart:io';
	import 'dart:async';
	import 'package:path_provider/path_provider.dart';
	import 'package:image/image.dart' as img;
	import 'package:flutter/rendering.dart';
	import 'dart:typed_data';
	import 'dart:ui' as ui;
	import 'modifiedscreen.dart';
	

	import 'package:graphql_flutter/graphql_flutter.dart';
	

	import 'addStar.dart' as mutations;
	import 'readRepositories.dart' as queries;
	import 'feedList.dart' as feedList;
	

	void main() {
	  runApp(MyApp());
	}
	

	class MyApp extends StatelessWidget {
	  @override
	  Widget build(BuildContext context) {
	    ValueNotifier<Client> client = ValueNotifier(
	      Client(
	        endPoint: 'https://api.github.com/graphql',
	        cache: InMemoryCache(),
	        apiToken: '<Enter your token here>',
	      ),
	    );
	

	    return GraphqlProvider(
	      client: client,
	      child: CacheProvider(
	        child: MaterialApp(
	          title: 'Flutter GraphQL Example',
	          theme: ThemeData(
	            primarySwatch: Colors.blue,
	          ),
	          home: MyHomePage(title: 'Flutter GraphQL Example'),
	        ),
	      ),
	    );
	  }
	}
	

	class MyHomePage extends StatefulWidget {
	  MyHomePage({
	    Key key,
	    this.title,
	  }) : super(key: key);
	

	  final String title;
	

	  @override
	  _MyHomePageState createState() => _MyHomePageState();
	}
	

	class _MyHomePageState extends State<MyHomePage> {
	  @override
	  Widget build(BuildContext context) {
	    return Scaffold(
	      appBar: AppBar(
	        title: Text(widget.title),
	      ),
	      body: Query(
	        "query ReadRepositories {" +
	            "    viewer {" +
	            "      repositories(last: 50) {" +
	            "        nodes {" +
	            "          id" +
	            "          name" +
	            "          viewerHasStarred" +
	            "        }" +
	            "      }" +
	            "    }" +
	            "  }",
	        builder: ({
	          bool loading,
	          Map data,
	          Exception error,
	        }) {
	          if (error != null) {
	            return Text(error.toString());
	          }
	

	          if (loading) {
	            return Text('Loading');
	          }
	          
	

	          // it can be either Map or List
	          List feedList = data['viewer']['repositories']['nodes'];
	

	          return ListView.builder(
	            itemCount: feedList.length,
	            itemBuilder: (context, index) {
	              final feedListItems = feedList[index];
	              // List tagList = feedListItems['name'];              
	              return new Card(
	                margin: const EdgeInsets.all(10.0),
	                child: ListTile(
	                  title: new Text(feedListItems['name']),
	                ),
	              );
	            },
	          );
	        },
	      ),
	    );
	  }
	}

 Setup coding accordingly as shown above in screenshot and Script

Your application will be ready in above steps.

Show some ??by hitting ??.

Happy Coding ?????

要查看或添加评论,请登录

Chirag Jadav的更多文章

社区洞察

其他会员也浏览了