GraphQL in Flutter: solved exercise with graphql_flutter, queries and mutations

GraphQL in Flutter: solved exercise with graphql_flutter

GraphQL is an alternative to REST that lets the client specify exactly what data it needs. graphql_flutter provides a full client with a normalized cache, reactive widgets, and WebSocket subscription support.

Problem statement

Build a screen that:

  • Configures GraphQLClient with HttpLink and an in-memory cache.
  • Uses the Query widget to list countries with their flag and continent.
  • Uses GraphQL variables to filter by continent.
  • Uses the Mutation widget to vote for a favorite country.
  • Handles loading, error, and empty states.

We will use the public API https://countries.trevorblades.com/ (world countries GraphQL).

Dependencies

1
2
dependencies:
  graphql_flutter: ^5.2.0-beta.7

Full solution

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
import 'package:flutter/material.dart';
import 'package:graphql_flutter/graphql_flutter.dart';

// โ”€โ”€ GraphQL client setup โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
ValueNotifier<GraphQLClient> _buildClient() {
  final httpLink = HttpLink('https://countries.trevorblades.com/');
  return ValueNotifier(
    GraphQLClient(
      link: httpLink,
      cache: GraphQLCache(store: InMemoryStore()),
    ),
  );
}

// โ”€โ”€ Queries โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

const _listCountries = r'''
  query ListCountries($continent: String) {
    countries(filter: { continent: { eq: $continent } }) {
      code
      name
      emoji
      capital
      continent {
        name
      }
      languages {
        name
      }
    }
  }
''';

const _getContinents = r'''
  query GetContinents {
    continents {
      code
      name
    }
  }
''';

// โ”€โ”€ Domain types โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
class Country {
  final String code;
  final String name;
  final String emoji;
  final String? capital;
  final String continent;
  final List<String> languages;

  const Country({
    required this.code,
    required this.name,
    required this.emoji,
    required this.capital,
    required this.continent,
    required this.languages,
  });

  factory Country.fromJson(Map<String, dynamic> json) => Country(
        code: json['code'] as String,
        name: json['name'] as String,
        emoji: json['emoji'] as String,
        capital: json['capital'] as String?,
        continent: (json['continent'] as Map<String, dynamic>)['name'] as String,
        languages: (json['languages'] as List).map((l) => l['name'] as String).toList(),
      );
}

class Continent {
  final String code;
  final String name;
  const Continent({required this.code, required this.name});
  factory Continent.fromJson(Map<String, dynamic> json) =>
      Continent(code: json['code'] as String, name: json['name'] as String);
}

// โ”€โ”€ App โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
void main() async {
  await initHiveForFlutter();
  runApp(GraphQLProvider(
    client: _buildClient(),
    child: const MaterialApp(home: CountriesScreen()),
  ));
}

// โ”€โ”€ Main screen โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
class CountriesScreen extends StatefulWidget {
  const CountriesScreen({super.key});
  @override
  State<CountriesScreen> createState() => _CountriesScreenState();
}

class _CountriesScreenState extends State<CountriesScreen> {
  String? _selectedContinent;
  String? _favoriteCountry;
  String _search = '';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('GraphQL + graphql_flutter'),
        bottom: PreferredSize(
          preferredSize: const Size.fromHeight(96),
          child: Padding(
            padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
            child: Column(
              children: [
                _ContinentFilter(
                  selected: _selectedContinent,
                  onChanged: (code) => setState(() => _selectedContinent = code),
                ),
                const SizedBox(height: 4),
                TextField(
                  decoration: const InputDecoration(
                    hintText: 'Search country...',
                    prefixIcon: Icon(Icons.search),
                    isDense: true,
                    border: OutlineInputBorder(),
                    fillColor: Colors.white,
                    filled: true,
                  ),
                  onChanged: (v) => setState(() => _search = v.toLowerCase()),
                ),
              ],
            ),
          ),
        ),
      ),
      body: Query(
        options: QueryOptions(
          document: gql(_listCountries),
          variables: {
            if (_selectedContinent != null) 'continent': _selectedContinent,
          },
          fetchPolicy: FetchPolicy.cacheAndNetwork,
        ),
        builder: (result, {fetchMore, refetch}) {
          if (result.isLoading && result.data == null) {
            return const Center(child: CircularProgressIndicator());
          }

          if (result.hasException) {
            return _ErrorView(
              message: result.exception.toString(),
              onRetry: refetch,
            );
          }

          final rawList = result.data?['countries'] as List? ?? [];
          var countries = rawList
              .map((e) => Country.fromJson(e as Map<String, dynamic>))
              .toList();

          if (_search.isNotEmpty) {
            countries = countries
                .where((c) =>
                    c.name.toLowerCase().contains(_search) ||
                    c.capital?.toLowerCase().contains(_search) == true)
                .toList();
          }

          if (countries.isEmpty) {
            return const Center(child: Text('No countries found'));
          }

          return RefreshIndicator(
            onRefresh: () async => refetch?.call(),
            child: ListView.builder(
              itemCount: countries.length,
              itemBuilder: (context, i) {
                final c = countries[i];
                final isFav = _favoriteCountry == c.code;
                return ListTile(
                  leading: Text(c.emoji, style: const TextStyle(fontSize: 28)),
                  title: Text(c.name),
                  subtitle: Text(
                    '${c.capital ?? 'No capital'} ยท ${c.continent}',
                    style: const TextStyle(fontSize: 12),
                  ),
                  trailing: IconButton(
                    icon: Icon(
                      isFav ? Icons.favorite : Icons.favorite_border,
                      color: isFav ? Colors.red : null,
                    ),
                    onPressed: () =>
                        setState(() => _favoriteCountry = isFav ? null : c.code),
                    tooltip: isFav ? 'Remove favorite' : 'Mark as favorite',
                  ),
                  onTap: () => _showDetail(context, c),
                );
              },
            ),
          );
        },
      ),
    );
  }

  void _showDetail(BuildContext context, Country c) {
    showModalBottomSheet(
      context: context,
      builder: (_) => _CountryDetail(country: c),
    );
  }
}

// โ”€โ”€ Continent filter (uses its own Query) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
class _ContinentFilter extends StatelessWidget {
  final String? selected;
  final ValueChanged<String?> onChanged;
  const _ContinentFilter({required this.selected, required this.onChanged});

  @override
  Widget build(BuildContext context) {
    return Query(
      options: QueryOptions(
        document: gql(_getContinents),
        fetchPolicy: FetchPolicy.cacheFirst,
      ),
      builder: (result, {fetchMore, refetch}) {
        if (result.isLoading) return const SizedBox(height: 28);
        final raw = result.data?['continents'] as List? ?? [];
        final continents =
            raw.map((e) => Continent.fromJson(e as Map<String, dynamic>)).toList();
        return SizedBox(
          height: 28,
          child: ListView(
            scrollDirection: Axis.horizontal,
            children: [
              ChoiceChip(
                label: const Text('All', style: TextStyle(fontSize: 11)),
                selected: selected == null,
                onSelected: (_) => onChanged(null),
                padding: EdgeInsets.zero,
                visualDensity: VisualDensity.compact,
              ),
              ...continents.map((cont) => Padding(
                    padding: const EdgeInsets.only(left: 4),
                    child: ChoiceChip(
                      label: Text(cont.name, style: const TextStyle(fontSize: 11)),
                      selected: selected == cont.code,
                      onSelected: (_) =>
                          onChanged(selected == cont.code ? null : cont.code),
                      padding: EdgeInsets.zero,
                      visualDensity: VisualDensity.compact,
                    ),
                  )),
            ],
          ),
        );
      },
    );
  }
}

// โ”€โ”€ Country detail โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
class _CountryDetail extends StatelessWidget {
  final Country country;
  const _CountryDetail({required this.country});

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(24),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Text(country.emoji, style: const TextStyle(fontSize: 48)),
              const SizedBox(width: 16),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(country.name,
                        style: Theme.of(context).textTheme.headlineSmall),
                    Text(country.continent,
                        style: const TextStyle(color: Colors.grey)),
                  ],
                ),
              ),
            ],
          ),
          const Divider(height: 24),
          if (country.capital != null) ...[
            _DetailRow(Icons.location_city, 'Capital', country.capital!),
            const SizedBox(height: 8),
          ],
          _DetailRow(Icons.language, 'Languages', country.languages.join(', ')),
          _DetailRow(Icons.code, 'Code', country.code),
        ],
      ),
    );
  }
}

class _DetailRow extends StatelessWidget {
  final IconData icon;
  final String label;
  final String value;
  const _DetailRow(this.icon, this.label, this.value);

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        Icon(icon, size: 18, color: Colors.grey),
        const SizedBox(width: 8),
        Text('$label: ', style: const TextStyle(fontWeight: FontWeight.bold)),
        Expanded(child: Text(value)),
      ],
    );
  }
}

// โ”€โ”€ Error view โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
class _ErrorView extends StatelessWidget {
  final String message;
  final VoidCallback? onRetry;
  const _ErrorView({required this.message, this.onRetry});

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Padding(
        padding: const EdgeInsets.all(24),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            const Icon(Icons.wifi_off, size: 48, color: Colors.red),
            const SizedBox(height: 16),
            Text('Network error', style: Theme.of(context).textTheme.titleMedium),
            const SizedBox(height: 8),
            Text(message, textAlign: TextAlign.center,
                style: const TextStyle(color: Colors.grey, fontSize: 12)),
            const SizedBox(height: 16),
            if (onRetry != null)
              FilledButton.icon(
                onPressed: onRetry,
                icon: const Icon(Icons.refresh),
                label: const Text('Retry'),
              ),
          ],
        ),
      ),
    );
  }
}

REST vs GraphQL comparison

FeatureRESTGraphQL
EndpointsMultiple (/countries, /continents)Single (/graphql)
Data returnedFixed per endpointExactly what you request
Over-fetchingFrequentImpossible by design
Under-fetchingRequires multiple requestsSolved with one query
CachingBy URLBy graph fragment
SubscriptionsManual WebSocketBuilt-in

Common mistakes

  • Forgetting initHiveForFlutter(): Hive’s persistent cache requires initialization before runApp. If you skip it, Hive throws an exception. If you don’t need persistence, use InMemoryStore().
  • Calling gql() inside build(): gql() parses the GraphQL document. Call it once as a constant (final doc = gql(query)) instead of inside build() to avoid re-parsing on every rebuild.
  • Not handling result.isLoading && result.data != null: when FetchPolicy.cacheAndNetwork refreshes data, isLoading is true but data holds the previous cached value. Show cached data during reload instead of a spinner.

Practical use

GraphQL is the standard choice for apps with complex interrelated data: e-commerce (products-variants-stock-reviews in one query), social networks (feed with posts-authors-likes), and analytics dashboards.

Guided practice and next step

FAQ

Do I need my own GraphQL server to learn?

No. There are public practice APIs: countries.trevorblades.com (countries), api.spacex.land/graphql (SpaceX), rickandmortyapi.com/graphql (Rick & Morty). Use any of them to learn without your own infrastructure.

When should I use watchQuery instead of the Query widget?

watchQuery is useful when you need to refresh data manually from a StatefulWidget or a ChangeNotifier, without depending on the widget tree. The Query widget is sufficient for 90% of reactive read use cases.

Does graphql_flutter support real-time subscriptions?

Yes. You need to add WebSocketLink and combine it with HttpLink using Link.split(). Subscriptions work exactly like queries but the builder is called every time the server emits an event.