Implement GraphQL with Flutter
GraphQL is a query language, which is used for API. It allows the client to exact data they need from the server(API), With the help of a query, we exact the specific data or component from the server. GraphQL is designed to make APIs pliable and suitable to use so that they are easier to develop. GraphQL helps you to build complex apps.
Table Of Contents:
What is GraphQL:-
GraphQL has many edges compared to REST. Rather than using a fixed data structure approach, GraphQL requests specific data the client requires. REST retaliation is notorious for holding too much data or not enough. GraphQL deciphers this by fetching exact data in a single request. GraphQL also has an introversion feature that allows developers to check types & the schema to secure they’re querying for data the right way.
Add Dependency:-
In your project goes to the pubspec. yaml and add the dependencies under the dependencies: add the latest version of graphql_flutter.
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.2
graphql_flutter: ^5.1.0
Usage of GraphQL:-
GraphQL is very useful for any flutter project who have complex APIs. It is an easy way to fetch the exact data from any Server(API).
GraphQLClient:
For fetching the data first we need to create a client for connecting to the server(API). To connect to the server we use GraphQLClient. GraphQLClient has two required properties cache and link.
final HttpLink httpLink =
HttpLink("https://countries.trevorblades.com/");
final ValueNotifier<GraphQLClient> client = ValueNotifier<GraphQLClient>(
GraphQLClient(
link: httpLink as Link,
cache: OptimisticCache(
dataIdFromObject: typenameDataIdFromObject,
),
),
In this code, as you can see, we create a final Httplink in which we pass the server link(API). And we create a client by using the ValueNotifier in which we pass GraphQLClient. ValueNotifier extends ChangeNotifier implements ValueListenable.
GraphQLClient({
required Link link,
required GraphQLCache cache,
DefaultPolicies? defaultPolicies,
bool alwaysRebroadcast = false,
})
In GraphQLClient we have two properties, link, and client. The Link over which GraphQL documents will be resolved into a Response. In our example, we use GitHub Public API. in which we pass the HTTP link. And we use Cache to store the initial data.
GraphQLProvider:
In GraphQLProvider we pass two parameters, child and client. We already created a client by which we can fetch the server’s data and also store the initial data in the cache. We pass the client as a client and also navigate the next page on which we want to show the data in the child parameter.
GraphQLProvider(
child: HomePage(),
client: client,
);
This is the Syntax of GraphQLProvider:
(new) GraphQLProvider GraphQLProvider({
Key? key,
ValueNotifier ? client,
Widget? child, })
Query:
To fetch the exact data we use query. creating a query is very simple and easy we use GitHub Public API.
In the above picture, we saw a query in which we get the data of all continents’ names and codes.
final String query = r"""
query GetContinent($code : String!){
continent(code:$code){
name
countries{
name
}
}
}
""";
In this, we create a string of queries and use r “”” “”” for writing any query and write a query by which we fetch the data.
After that, we pass the query in Scaffold’s body as a widget.
(new) Query Query({
Key? key,
required QueryOptions options,
required Widget Function(QueryResult ,
{
Future > Function(FetchMoreOptions)? fetchMore, Future ?> Function()? refetch
})
builder, })
In this, we use two parameters in the query, Options, and builder. In QueryOptions we use documents to pass the query which we already defined as a string and we also pass variables in which we pass the code of the country.
options: QueryOptions(
document: query,
variables: <String, dynamic>{"code": "AS"}),
we can also pass many things in options like duration, Context, Object, Operation-name, DocumentNode, FetchPolicy, ErrorPolicy, etc.
(new) QueryOptions QueryOptions
({
required DocumentNode document,
String? operationName,
Map variables = const {},
FetchPolicy? fetchPolicy,
ErrorPolicy? errorPolicy,
CacheRereadPolicy? cacheRereadPolicy,
Object? optimisticResult,
Duration? pollInterval,
Context? context,
Object? Function(Map )? parserFn,
})
we use FetchMoreOption inside Query Builder to perform pagination. Function permits you to run an entirely new GraphQL operation and amalgamate the new results with the original results. You can re-use features of the Original query i.e. the Query or some of the Variables.
builder: (
QueryResult result, {
VoidCallback refetch,
}) {
if (result.loading) {
return Center(child: CircularProgressIndicator());
}
if (result.data == null) {
return Text("No Data Found !");
}
return ListView.builder(
itemBuilder: (BuildContext context, int index) {
return ListTile(
title:
Text(result.data['continent']['countries'][index]['name']),
);
},
itemCount: result.data['continent']['countries'].length,
);
},
),
In the builder, we use QueryResult to fetch the final result and create a voidcallback by using fetch. And we add a condition when the result is loading so its shows a CircularProgressIndicator(), and if there is no data in the list so it shows NO DATA FOUND. And return ListView.Builder(), in item builder we pass context and index and return the ListTile for printing the country name as a list and in the itemCount, we pass the length of a list.
Mutation:
The Mutation is used to update and insert data like for post/delete/put requests. The syntax for mutations is fairly similar to that of a query. The only difference is that the first quarrel of the builder function is a mutation function. Just call it to activate the mutations.
Mutation(
options: MutationOptions(
document: gql(addStar),
update: (GraphQLDataProxy cache, QueryResult result) {
return cache;
},
onCompleted: (dynamic resultData) {
print(resultData);
},
),
builder: (
RunMutation runMutation,
QueryResult result,
) {
return FloatingActionButton(
onPressed: () => runMutation({
'starrableId': <A_STARTABLE_REPOSITORY_ID>,
}),
tooltip: 'Star',
child: Icon(Icons.star),
);
},
);
Conclusion:-
In this article, we almost covered the very topic of GraphQL. We started by introducing, what GraphQL is and how it works. Then, we introduced graphql_flutter with examples of how to make queries, and mutations, from a Flutter app.
❤ ❤ Thanks for reading this article ❤❤
If I got something wrong? Let me know in the comments. I would love to improve.
Clap 👏 If this article helps you.
GitHub Link:
Find the source code of the Implementing GraphQL in Flutter
GitHub – flutter-devs/graphql_demo
You can’t perform that action at this time. You signed in with another tab or window. You signed out in another tab or…github.com
❤ ❤ Thanks for reading this article ❤❤
If I got something wrong? Let me know in the comments. I would love to improve.
Clap 👏 If this article helps you.
Feel free to connect with us:
And read more articles from FlutterDevs.com.
FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on Facebook, GitHub, Twitter, and LinkedIn for any flutter-related queries.
We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.