Implementation suggestions for GraphQL + Riverpod + Freezed in Flutter
Table of Content
Introduction
Packages used
Let’s implement
Summary
Introduction
This article is for those who are familiar with Riverpod and Freezed and are new to using them with graphql. Here is a sample code that uses graphql and Freezed together. It is possible to use model classes automatically generated by the graphql client. It was very difficult to handle because different queries for the same type would create different classes. The implementation of model classes generated by Freezed is difficult to write, but once created, it is highly compatible with Riverpod and very easy to use.
Packages used
Let’s implement
Explanatory scenario
Let us consider a scenario in which we need to retrieve order information for a certain product. The order information contains information about the ordered product and the user who placed the order.
Get schema.graphql from server side
Now, before we start implementation, let’s get schema.graphql. Ask the server side people. And ask them to provide this. The schema.graphql used in this project is as follows.
Make query(xxxxxx.graphql) that you need
Let’s implement a query to retrieve order information. In this case, I have done the following.
Run build_runner
Run build_runner with the following command.
$ flutter pub run build_runner build — delete-conflicting-outputs
Generate GraphQL requests and responses written in Dart from GraphQL sources. Those codes are stored in the __gererated__ folder.
Make model using freezed
Define Order, User, and Products types as models.
Make graphql service using model from query
Convert response of query to Order Model.
Make Graphql client
A service class that executes a query.
Provide model instance
Now the response obtained by graphql can be used in Freezed and Riverpod.
final service = ref.watch(orderServiceProvider);
final order = service.fetch(id: 'order_id');
Summary
It is time consuming to handle graphql responses with Freezed. If anyone knows of an automated tool, please let me know.