Add conditions to hide or show additional fields based on information entered
Hygraph
Classic Docs

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.

#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 project

After 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 permissionsContent 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.dart
import '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.dart
final 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.dart
const String query = """
query Posts{
posts{
id
publishedAt
title
excerpt
coverImage {
url
}
author {
id
name
}
}
}
""";

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.dart
import '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.dart
import '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 API
final 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 posts
const String query = """
query Posts{
posts{
id
publishedAt
title
excerpt
coverImage {
url
}
author {
id
name
}
}
}
""";
// Main widget
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,
);
},
);
}),
)),
);
}
}

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 appFlutter iOS app

#Web app

Flutter web appFlutter 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!