Using Hasura GraphQL as a Backend for Flutter Projects
Hello everyone, today we will examine GraphQL databases from a Flutter developer’s perspective.
Setup Process
We will be using Heroku to deploy Hasura with a click of a button. As seen from this link, you can easily deploy Hasura GraphQL engine clicking the purple button and proceeding with the login procedure.
After the setup, Hasura will be quickly deployed to the web and you will be able to start using it. Ideally, it will also install postgres plugin automatically and link it to the engine but in my case, it didn’t. So I’ll show you how I fixed it.
Add Postgres DB to Hasura Engine (Optional)
Go the this link and find the postgres datastore affiliated. If there is none, create one. Then go the settings and click on View Credentials… This will show up private credential information to you, from there, copy the uri section completely
After copying this uri, go Heroku dashboard and click on Open App to open deployed Hasura Engine. Then go into the Data tab and you’ll see that it wants you to connect a postgres database to it. Name the database whatever you want, choose PostgreSQL as Data Source Driver and paste in the uri you copied as the Database URL.
After connecting, you’ll be good to go!
For the sake of simplicity, I wanted to build a simple todo app. So I created a table called todos.
After this phase, you can start to play around with the GraphiQL to try and understand it more. The basic CRUD operations are split between Query and Mutation in GraphQL. Query’s are for reading the exact data you wanted. Mutations are for everything else; create, update and delete. In GraphQL, the result are always returned as JSON’s even though it is a structured SQL database.
Connecting GraphQL Database with a Flutter Project
Although there are several pub packages available for the task, I chose graphql package for it. In this package, to run queries and mutations, we first need to get client as GraphQLClient.
Run queries
Now lets run a query with it. After running the query, the result will also return data as Map<String, dynamic>? to us meaning an easy to parse JSON file.
With these two in place, we can get todos in provider under a single function. This method also calls notifyListeners(), so we can listen to mainTodos from the UI and directly update it accordingly.
Run mutations
Similar to queries, we’ll need to provide a query to the client. If there are any, we also need to provide variables.
You can check out the entire project on my github profile