Tutorial: Integrating GraphQL with Flutter

Tutorial: Integrating GraphQL with Flutter

Yo wasup Flutter devs!

Today, we're diving deep into the world of GraphQL and Flutter. By the end of this tutorial, you'll have a solid understanding of how to integrate GraphQL with your Flutter apps.

So, grab your favorite beverage, and let's get started!


1. Why GraphQL?

Before we jump into the integration, let's quickly touch upon why you might want to use GraphQL:

  • Flexibility: Request only the data you need.

  • Strongly Typed: No more guessing about data types.

  • Single Endpoint: Say goodbye to multiple REST endpoints.


2. Setting Up Your Flutter Project

First things first, create a new Flutter project:

flutter create graphql_flutter_app
cd graphql_flutter_app

3. Dependencies

Add the necessary dependencies to your pubspec.yaml:

dependencies:
  flutter:
    sdk: flutter
  graphql_flutter: ^latest_version_here

Run flutter pub get to install them.


4. Setting Up GraphQL Client

Create a new file graphql_client.dart:

import 'package:flutter/material.dart';
import 'package:graphql_flutter/graphql_flutter.dart';

ValueNotifier<GraphQLClient>? clientFor({required String uri}) {
  final HttpLink httpLink = HttpLink(uri);

  final ValueNotifier<GraphQLClient> client = ValueNotifier<GraphQLClient>(
    GraphQLClient(
      link: httpLink,
      cache: GraphQLCache(store: InMemoryStore()),
    ),
  );

  return client;
}

5. Wrap Your App

In your main.dart, wrap your app with GraphQLProvider and CacheProvider:

import 'package:graphql_flutter/graphql_flutter.dart';
import 'graphql_client.dart';

void main() {
  final client = clientFor(uri: 'https://your-graphql-endpoint.com');
  runApp(MyApp(client: client!));
}

class MyApp extends StatelessWidget {
  final ValueNotifier<GraphQLClient> client;

  MyApp({required this.client});

  @override
  Widget build(BuildContext context) {
    return GraphQLProvider(
      client: client,
      child: CacheProvider(
        child: MaterialApp(
          title: 'GraphQL Flutter',
          home: HomePage(),
        ),
      ),
    );
  }
}

6. Crafting Queries

For this tutorial, let's assume we're fetching a list of books. Create a new file queries.dart:

const String getBooks = r'''
  query GetBooks {
    books {
      title
      author
    }
  }
''';

7. Fetching Data

In your HomePage widget:

import 'package:graphql_flutter/graphql_flutter.dart'; import 'queries.dart';

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('GraphQL Flutter')),
      body: Query(
        options: QueryOptions(document: gql(getBooks)),
        builder: (QueryResult? result, {VoidCallback? refetch, FetchMore? fetchMore}) {
          if (result!.hasException) {
            return Text(result.exception.toString());
          }

          if (result.isLoading) {
            return CircularProgressIndicator();
          }

          final books = result.data?['books'];
          return ListView.builder(
            itemCount: books?.length ?? 0,
            itemBuilder: (context, index) {
              final book = books![index];
              return ListTile(
                title: Text(book['title']),
                subtitle: Text(book['author']),
              );
            },
          );
        },
      ),
    );
  }
}

8. Mutations

If you want to modify data, GraphQL has mutations. Here's a quick example:

const String addBook = r'''
  mutation AddBook($title: String!, $author: String!) {
    addBook(title: $title, author: $author) {
      title
      author
    }
  }
''';

// In your widget:
Mutation(
  options: MutationOptions(document: gql(addBook)),
  builder: (RunMutation runMutation, QueryResult? result) {
    return ElevatedButton(
      onPressed: () {
        runMutation({'title': 'New Book', 'author': 'John Doe'});
      },
      child: Text('Add Book'),
    );
  },
);

9. Conclusion

And there you have it! A concise, end-to-end guide on integrating GraphQL with Flutter. With GraphQL's flexibility and Flutter's ease of use, you're now equipped to build powerful apps with a streamlined data-fetching process.

Remember, practice makes perfect. So, play around, experiment, and happy coding! 🚀


Before We Go...

Hey, thanks for sticking around! If this post was your jam, imagine what’s coming up next.

I’m launching a YouTube channel, and trust me, you don't want to miss out. Give it a look and maybe even hit that subscribe button?

Tap to subscribe.

Until we meet again, code on and stay curious!

Got any doubt or wanna chat? React out to me on twitter or linkedin.