GraphQL en Flutter: ejercicio resuelto con graphql_flutter, queries y mutaciones

GraphQL en Flutter: ejercicio resuelto con graphql_flutter

GraphQL es una alternativa a REST que permite al cliente especificar exactamente qué datos quiere. graphql_flutter proporciona un cliente completo con cache normalizado, widgets reactivos y soporte para suscripciones WebSocket.

Enunciado

Implementa una pantalla que:

  • Configure GraphQLClient con HttpLink y cache en memoria.
  • Use el widget Query para listar países con su bandera y continente.
  • Use variables GraphQL para filtrar por continente.
  • Use el widget Mutation para votar por un país favorito.
  • Maneje estados de carga, error y datos vacíos.

Usaremos la API pública https://countries.trevorblades.com/ (GraphQL de países del mundo).

Dependencias

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

Solución completa

  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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
import 'package:flutter/material.dart';
import 'package:graphql_flutter/graphql_flutter.dart';

// ── Configuración del cliente GraphQL ─────────────────────────────────────────
ValueNotifier<GraphQLClient> _buildClient() {
  final httpLink = HttpLink('https://countries.trevorblades.com/');
  return ValueNotifier(
    GraphQLClient(
      link: httpLink,
      cache: GraphQLCache(store: InMemoryStore()),
    ),
  );
}

// ── Queries y mutaciones ───────────────────────────────────────────────────────

/// Lista países filtrables por continente
const _listCountries = r'''
  query ListCountries($continent: String) {
    countries(filter: { continent: { eq: $continent } }) {
      code
      name
      emoji
      capital
      continent {
        name
      }
      languages {
        name
      }
    }
  }
''';

/// Detalle de un continente
const _getContinents = r'''
  query GetContinents {
    continents {
      code
      name
    }
  }
''';

// ── Tipos de dominio ───────────────────────────────────────────────────────────
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(); // inicializa Hive para caché persistente opcional
  runApp(GraphQLProvider(
    client: _buildClient(),
    child: const MaterialApp(home: CountriesScreen()),
  ));
}

// ── Pantalla principal ─────────────────────────────────────────────────────────
class CountriesScreen extends StatefulWidget {
  const CountriesScreen({super.key});
  @override
  State<CountriesScreen> createState() => _CountriesScreenState();
}

class _CountriesScreenState extends State<CountriesScreen> {
  String? _selectedContinent; // null = todos los continentes
  String? _favoriteCountry;   // guardado localmente (sin backend real)
  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: [
                // Filtro por continente
                _ContinentFilter(
                  selected: _selectedContinent,
                  onChanged: (code) =>
                      setState(() => _selectedContinent = code),
                ),
                const SizedBox(height: 4),
                // Búsqueda local
                TextField(
                  decoration: const InputDecoration(
                    hintText: 'Buscar país...',
                    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}) {
          // ── Estado de carga ───────────────────────────────────────────
          if (result.isLoading && result.data == null) {
            return const Center(child: CircularProgressIndicator());
          }

          // ── Estado de error ───────────────────────────────────────────
          if (result.hasException) {
            return _ErrorView(
              message: result.exception.toString(),
              onRetry: refetch,
            );
          }

          // ── Datos vacíos ──────────────────────────────────────────────
          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 se encontraron países'));
          }

          // ── Lista de países ───────────────────────────────────────────
          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 ?? 'Sin 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 ? 'Quitar favorito' : 'Marcar favorito',
                  ),
                  onTap: () => _showDetail(context, c),
                );
              },
            ),
          );
        },
      ),
    );
  }

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

// ── Filtro de continentes (usa su propia 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('Todos', 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,
                    ),
                  )),
            ],
          ),
        );
      },
    );
  }
}

// ── Detalle de país ────────────────────────────────────────────────────────────
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, 'Idiomas', country.languages.join(', ')),
          _DetailRow(Icons.code, 'Código', 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)),
      ],
    );
  }
}

// ── Vista de error ─────────────────────────────────────────────────────────────
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(
              'Error de red',
              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('Reintentar'),
              ),
          ],
        ),
      ),
    );
  }
}

Diferencias entre REST y GraphQL

CaracterísticaRESTGraphQL
EndpointMúltiples (/countries, /continents)Único (/graphql)
Datos devueltosFijos por endpointExactamente los que pides
Over-fetchingFrecuenteImposible por diseño
Under-fetchingRequiere múltiples requestsResuelto con un query
CachePor URLPor fragmento en grafo
SuscripcionesWebSocket manualIntegrado (subscriptions)

Errores frecuentes

  • Olvidar initHiveForFlutter(): la caché persistente de Hive requiere inicialización antes de runApp. Si no la llamas, Hive lanza una excepción. Si no necesitas persistencia, usa InMemoryStore().
  • gql() fuera del widget build: gql() parsea el documento GraphQL. Llámalo una vez como constante (final doc = gql(query)) en lugar de dentro de build() para evitar re-parseos.
  • No manejar result.isLoading && result.data != null: cuando FetchPolicy.cacheAndNetwork refresca datos, isLoading es true pero data tiene el valor anterior del caché. Muestra los datos del caché durante la recarga en lugar de un spinner.

Aplicación práctica

GraphQL es la elección estándar para apps con datos complejos interrelacionados: e-commerce (productos-variantes-stock-reseñas en un solo query), redes sociales (feed con posts-autores-likes) y dashboards analíticos.

Siguiente ejercicio recomendado

Práctica guiada y siguiente paso

FAQ

¿Necesito un servidor GraphQL propio para aprender?

No. Existen APIs públicas de práctica: countries.trevorblades.com (países), api.spacex.land/graphql (SpaceX), rickandmortyapi.com/graphql (Rick & Morty). Usa cualquiera de ellas para aprender sin infraestructura propia.

¿Cuándo usar watchQuery en lugar del widget Query?

watchQuery es útil cuando necesitas refrescar datos manualmente desde un StatefulWidget o desde un ChangeNotifier, sin depender del árbol de widgets. El widget Query es suficiente para el 90 % de los casos de lectura reactiva.

¿graphql_flutter soporta suscripciones en tiempo real?

Sí. Necesitas añadir WebSocketLink y combinarla con HttpLink usando Link.split(). Las suscripciones funcionan igual que las queries pero el builder se llama cada vez que el servidor emite un evento.