Flutter + Hygraph
#Overview
Flutter is a cross-platform software development kit (SDK) for mobile app development that uses Dart programming language to create apps for Android and iOS devices.
#Prerequisites
To follow along, the following prerequisites are required.
- Flutter SDK and all of its dependencies installed on your machine
- Basic knowledge of Dart programming language
- A iOS simulator and/or Android studio installed on your machine
#Creating a new Flutter app
This guides covers how to connect a Flutter application to Hygraph and query content using a GraphQL client. To create a new Flutter app, run the following command:
flutter create <PROJECT_NAME_HERE>
#Getting data from Hygraph
Let's practice getting data from Hygraph. Start by cloning our blog app Hygraph project:
Click here to clone the projectAfter cloning, you will have a simple project that contains a few basic content models that would typically be used in a blog. The Post model contains fields such a title
, excerpt
, authorName
, and coverImage
and three sample blog posts in the Content section.
#Public content API
Before you can connect Flutter to Hygraph, you will need to configure Content API access permissions for unauthenticated requests.
To do this, go Project settings > Access > API Access > Content API in your Hygraph project, scroll to find the Content Permissions box that reads Would you like us to initialize some defaults?, and click Yes, initialize defaults
:
Content API permissions
Finally, copy the High Performance Content API
endpoint from Project settings > Access > API Access > Endpoints. You use it to connect Flutter to Hygraph later on.
#Testing a query in the API playground
Next, you should test if you can fetch the information from the sample blog posts in your project. To do this, navigate to the API Playground in your project and use the following query:
If you execute the query, the response should fetch all the sample blog posts in the demo project you cloned.
#Connecting Flutter to Hygraph
To practice connecting Hygraph to Flutter, clone the basic blog flutter app from our repository using the following command:
npx degit https://github.com/hygraph/flutter-hygraph-blog.git
#Installing graph_flutter
After cloning the blog app, navigate to the root of your project cd flutter-hygraph-blog
to add the graph_flutter
package to your Flutter project. This package provides a set of widgets that make it easy to run queries and mutations with our content from Hygraph in our Flutter project.
To install the GraphQL package, type the following command in the root directory of your Flutter project:
flutter pub add graphql_flutter
#Configuring the GraphQL client
After the installation completes, import the package in the lib/main.dart
file, using the following code:
// File location: lib/main.dartimport 'package:graphql_flutter/graphql_flutter.dart';
Now, we can use the GraphQLClient()
widget and Hygraph content API endpoint URL you copied earlier from your Hygraph project. Add the the endpoint URL to the HttpLink()
variable and pass it to the
GraphQLClient()
widget in the lib/main.dart
file:
// File location: lib/main.dartfinal HttpLink httpLink = HttpLink("https://<HYGRAPH_CDN_LOCATION>.cdn.hygraph.com/content/<ID>/master");final ValueNotifier<GraphQLClient> client = ValueNotifier<GraphQLClient>(GraphQLClient(link: httpLink,cache: GraphQLCache(),),);
That's it! You have successfully connected your Flutter app to Hygraph. You can now run queries and mutations to fetch content from your Hygraph project.
#Running a Posts query in Flutter
Let's run a query to fetch all the blog posts from your Hygraph project. Add the following code to your lib/main.dart
file just below your Hygraph GraphQL client configuration:
// File location: lib/main.dartconst String query = """query Posts{posts{idpublishedAttitleexcerptcoverImage {url}author {idname}}}""";
The above query fetches all blog posts from Hygraph and their field content such as id
, publishedAt
, title
, excerpt
, coverImage
, and author
. The great thing about GraphQL is that it allows you to query only the fields you need, which makes your queries faster and more efficient. This makes a difference with any application, but is especially important in mobile applications where data usage and speed are critical.
#Displaying the posts in a Flutter app
Your cloned Flutter app contains a directory called widgets
that contains a blog_row.dart
file that creates a BlogRow
widget for displaying the blog posts from Hygraph.
The BlogRow
widget is a StatelessWidget
that fetches the blog posts from Hygraph and displays them in a ListView
widget. In other words, it's a simple widget that displays the blog posts in a list that we can import and use in our main.dart
file.
Next, import the BlogRow
widget in your lib/main.dart
file and add the following code to display the blog posts in your Flutter app:
// File location: lib/main.dartimport 'widgets/blog_row.dart';class MyApp extends StatelessWidget {const MyApp({super.key});Widget build(BuildContext context) {return GraphQLProvider(client: client,child: MaterialApp(title: 'GraphQL Demo',theme: ThemeData(primarySwatch: Colors.blue,),home: Scaffold(appBar: AppBar(title: const Text("Hygraph blog app using Flutter",),),body: Query(options: QueryOptions(document: gql(query),variables: const <String, dynamic>{"code": "AF"}),builder: (result, {fetchMore, refetch}) {if (result.isLoading) {return const Center(child: CircularProgressIndicator(),);}if (result.data == null) {return const Center(child: Text("No article found!"),);}final posts = result.data!['posts'];return ListView.builder(itemCount: posts.length,itemBuilder: (context, index) {final post = posts[index];final title = post['title'];final excerpt = post['excerpt'];final coverImageURL = post!['coverImage']['url'];final authorName = post['author']['name'];return BlogRow(title: title,excerpt: excerpt,coverURL: coverImageURL,authorName: authorName,); // BlogRow widget},); // ListView.builder}), // Query)), // MaterialApp); // GraphQLProvider}}
#Code overview
The above code uses the returned content that we fetched from our blog posts query to display posts in a scrollable list using the ListView.builder
widget. The BlogRow
widget is used to display each blog post in the list.
#Putting all the Flutter pieces together
We have all these pieces we need to create the Main
widget or entry point of our Flutter app. Your lib/main.dart
file should have the following code and structure:
// File location: lib/main.dartimport 'widgets/blog_row.dart';import 'package:flutter/material.dart';import 'package:graphql_flutter/graphql_flutter.dart';void main() {runApp(const MyApp());}// Create GraphQL client and connect to Hygraph content APIfinal HttpLink httpLink = HttpLink("https://<HYGRAPH_CDN_LOCATION>.cdn.hygraph.com/content/<ID>/master");final ValueNotifier<GraphQLClient> client = ValueNotifier<GraphQLClient>(GraphQLClient(link: httpLink,cache: GraphQLCache(),),);// GraphQL query to fetch all blog postsconst String query = """query Posts{posts{idpublishedAttitleexcerptcoverImage {url}author {idname}}}""";// Main widgetclass MyApp extends StatelessWidget {const MyApp({super.key});Widget build(BuildContext context) {return GraphQLProvider(client: client,child: MaterialApp(title: 'GraphQL Demo',theme: ThemeData(primarySwatch: Colors.blue,),home: Scaffold(appBar: AppBar(title: const Text("Hygraph blog app using Flutter",),),body: Query(options: QueryOptions(document: gql(query),variables: const <String, dynamic>{"code": "AF"}),builder: (result, {fetchMore, refetch}) {if (result.isLoading) {return const Center(child: CircularProgressIndicator(),);}if (result.data == null) {return const Center(child: Text("No article found!"),);}final posts = result.data!['posts'];return ListView.builder(itemCount: posts.length,itemBuilder: (context, index) {final post = posts[index];final title = post['title'];final excerpt = post['excerpt'];final coverImageURL = post!['coverImage']['url'];final authorName = post['author']['name'];return BlogRow(title: title,excerpt: excerpt,coverURL: coverImageURL,authorName: authorName,);},);}),)),);}}
With everything in it's right place, you can now run your Flutter app using the following command:
flutter run
With Flutter running, your app should feature a list of blog posts, like so:
#Native iOS app
Flutter iOS app
#Web app
Flutter web app
Congratulations, you now have a Flutter Blog app that shows posts from Hygraph that is available to run cross-platform on iOS and Android devices as well as in a browser!
This was a simple and quick example of how to fetch and render content from Hygraph ina Flutter app.
For more complete implementation examples, follow a Flutter guide .