Volver a Artículos

Intermedio

Integración de API y Solicitudes HTTP en Flutter

· 12 min read

Introducción

La mayoría de las aplicaciones móviles modernas se comunican con APIs del lado del servidor para intercambiar datos. Hay varios enfoques para la integración de API en Flutter. En este artículo, examinaremos los métodos más populares y confiables en detalle.

Los temas principales a considerar al integrar APIs son: solicitudes HTTP (GET, POST, PUT, DELETE), análisis de datos JSON, manejo de errores, estados de carga y manejo de errores de red.

Instalación del Paquete HTTP

El paquete más popular para hacer solicitudes HTTP en Flutter es el paquete `http`. Para agregar este paquete a tu proyecto, necesitas agregarlo a tu archivo pubspec.yaml.

dependencies:
  flutter:
    sdk: flutter
  http: ^1.1.0
  provider: ^6.1.1

Después de agregar el paquete, ejecuta `flutter pub get` para instalarlo.

Solicitudes HTTP Básicas

Con el paquete HTTP, puedes hacer solicitudes GET, POST, PUT y DELETE. Comencemos con una solicitud GET simple:

import 'dart:convert';
import 'package:http/http.dart' as http;

class ApiService {
  // Definir URL base
  static const String baseUrl = 'https://jsonplaceholder.typicode.com';
  
  // Hacer solicitud GET
  Future<List<Map<String, dynamic>>> getPosts() async {
    try {
      final response = await http.get(
        Uri.parse('$baseUrl/posts'),
        headers: {
          'Content-Type': 'application/json',
        },
      );
      
      // Verificar código de estado
      if (response.statusCode == 200) {
        // Analizar JSON
        final List<dynamic> data = json.decode(response.body);
        return data.cast<Map<String, dynamic>>();
      } else {
        throw Exception('Failed to load posts: ${response.statusCode}');
      }
    } catch (e) {
      throw Exception('Network error: $e');
    }
  }
  
  // Hacer solicitud POST
  Future<Map<String, dynamic>> createPost({
    required String title,
    required String body,
    required int userId,
  }) async {
    try {
      final response = await http.post(
        Uri.parse('$baseUrl/posts'),
        headers: {
          'Content-Type': 'application/json',
        },
        body: json.encode({
          'title': title,
          'body': body,
          'userId': userId,
        }),
      );
      
      if (response.statusCode == 201) {
        return json.decode(response.body) as Map<String, dynamic>;
      } else {
        throw Exception('Failed to create post: ${response.statusCode}');
      }
    } catch (e) {
      throw Exception('Network error: $e');
    }
  }
}

En el código anterior, creamos una clase de servicio API básica. Esta clase puede hacer solicitudes GET y POST. Usamos bloques try-catch para el manejo de errores para cada solicitud.

Crear Clases Modelo

Crear clases modelo para gestionar mejor los datos que vienen de la API es importante. Esto proporciona seguridad de tipos y mejora la legibilidad del código.

class Post {
  final int id;
  final int userId;
  final String title;
  final String body;
  
  Post({
    required this.id,
    required this.userId,
    required this.title,
    required this.body,
  });
  
  // Crear objeto Post desde JSON
  factory Post.fromJson(Map<String, dynamic> json) {
    return Post(
      id: json['id'] as int,
      userId: json['userId'] as int,
      title: json['title'] as String,
      body: json['body'] as String,
    );
  }
  
  // Convertir objeto Post a JSON
  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'userId': userId,
      'title': title,
      'body': body,
    };
  }
  
  @override
  String toString() {
    return 'Post(id: $id, userId: $userId, title: $title)';
  }
}

Con la clase modelo, podemos usar datos JSON sin procesar de la API de manera segura en cuanto a tipos. El constructor factory `fromJson` crea un objeto desde JSON, mientras que el método `toJson` convierte el objeto a JSON.

Gestión de Estado con Provider

Usar gestión de estado para administrar llamadas API y actualizar la UI es importante. Veamos cómo hacer esto con el paquete Provider:

import 'package:flutter/foundation.dart';
import '../models/post.dart';
import '../services/api_service.dart';

class PostProvider with ChangeNotifier {
  final ApiService _apiService = ApiService();
  
  List<Post> _posts = [];
  bool _isLoading = false;
  String? _error;
  
  // Getters
  List<Post> get posts => _posts;
  bool get isLoading => _isLoading;
  String? get error => _error;
  
  // Cargar posts
  Future<void> loadPosts() async {
    _isLoading = true;
    _error = null;
    notifyListeners();
    
    try {
      final data = await _apiService.getPosts();
      _posts = data.map((json) => Post.fromJson(json)).toList();
      _error = null;
    } catch (e) {
      _error = e.toString();
      _posts = [];
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }
  
  // Crear nuevo post
  Future<bool> createPost({
    required String title,
    required String body,
    required int userId,
  }) async {
    _isLoading = true;
    _error = null;
    notifyListeners();
    
    try {
      final data = await _apiService.createPost(
        title: title,
        body: body,
        userId: userId,
      );
      
      // Agregar nuevo post a la lista
      final newPost = Post.fromJson(data);
      _posts.insert(0, newPost);
      _error = null;
      _isLoading = false;
      notifyListeners();
      return true;
    } catch (e) {
      _error = e.toString();
      _isLoading = false;
      notifyListeners();
      return false;
    }
  }
  
  // Limpiar posts
  void clearPosts() {
    _posts = [];
    notifyListeners();
  }
}

La clase Provider gestiona las llamadas API y actualiza la UI. Gracias al mixin `ChangeNotifier`, notifica a todos los oyentes cuando cambia el estado. Podemos mostrar estados de carga y error al usuario con los estados `isLoading` y `error`.

Implementación de UI

Ahora creemos una UI usando el Provider. Esta UI listará los posts y permitirá agregar nuevos posts:

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../providers/post_provider.dart';
import '../models/post.dart';

class PostsScreen extends StatefulWidget {
  const PostsScreen({super.key});

  @override
  State<PostsScreen> createState() => _PostsScreenState();
}

class _PostsScreenState extends State<PostsScreen> {
  final TextEditingController _titleController = TextEditingController();
  final TextEditingController _bodyController = TextEditingController();
  
  @override
  void initState() {
    super.initState();
    // Cargar posts cuando se abre la página
    WidgetsBinding.instance.addPostFrameCallback((_) {
      context.read<PostProvider>().loadPosts();
    });
  }
  
  @override
  void dispose() {
    _titleController.dispose();
    _bodyController.dispose();
    super.dispose();
  }
  
  Future<void> _showAddPostDialog() async {
    return showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('Agregar Nuevo Post'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            TextField(
              controller: _titleController,
              decoration: const InputDecoration(
                labelText: 'Título',
                border: OutlineInputBorder(),
              ),
            ),
            const SizedBox(height: 16),
            TextField(
              controller: _bodyController,
              decoration: const InputDecoration(
                labelText: 'Contenido',
                border: OutlineInputBorder(),
              ),
              maxLines: 3,
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('Cancelar'),
          ),
          ElevatedButton(
            onPressed: () async {
              final provider = context.read<PostProvider>();
              final success = await provider.createPost(
                title: _titleController.text,
                body: _bodyController.text,
                userId: 1,
              );
              
              if (success && mounted) {
                Navigator.pop(context);
                _titleController.clear();
                _bodyController.clear();
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(content: Text('¡Post agregado exitosamente!')),
                );
              } else if (mounted) {
                ScaffoldMessenger.of(context).showSnackBar(
                  SnackBar(content: Text('Error: ${provider.error}')),
                );
              }
            },
            child: const Text('Agregar'),
          ),
        ],
      ),
    );
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Posts'),
        actions: [
          IconButton(
            icon: const Icon(Icons.refresh),
            onPressed: () {
              context.read<PostProvider>().loadPosts();
            },
          ),
        ],
      ),
      body: Consumer<PostProvider>(
        builder: (context, provider, child) {
          // Estado de carga
          if (provider.isLoading && provider.posts.isEmpty) {
            return const Center(
              child: CircularProgressIndicator(),
            );
          }
          
          // Estado de error
          if (provider.error != null && provider.posts.isEmpty) {
            return Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  const Icon(
                    Icons.error_outline,
                    size: 64,
                    color: Colors.red,
                  ),
                  const SizedBox(height: 16),
                  Text(
                    'Error: ${provider.error}',
                    style: const TextStyle(color: Colors.red),
                    textAlign: TextAlign.center,
                  ),
                  const SizedBox(height: 16),
                  ElevatedButton(
                    onPressed: () => provider.loadPosts(),
                    child: const Text('Reintentar'),
                  ),
                ],
              ),
            );
          }
          
          // Lista de posts
          if (provider.posts.isEmpty) {
            return const Center(
              child: Text('Aún no hay posts'),
            );
          }
          
          return RefreshIndicator(
            onRefresh: () => provider.loadPosts(),
            child: ListView.builder(
              itemCount: provider.posts.length,
              padding: const EdgeInsets.all(8),
              itemBuilder: (context, index) {
                final post = provider.posts[index];
                return Card(
                  margin: const EdgeInsets.symmetric(vertical: 4),
                  child: ListTile(
                    title: Text(
                      post.title,
                      style: const TextStyle(fontWeight: FontWeight.bold),
                    ),
                    subtitle: Text(
                      post.body,
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                    ),
                    trailing: Text(
                      'ID: ${post.id}',
                      style: const TextStyle(fontSize: 12),
                    ),
                    onTap: () {
                      // Navegar a la página de detalle del post
                    },
                  ),
                );
              },
            ),
          );
        },
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _showAddPostDialog,
        child: const Icon(Icons.add),
      ),
    );
  }
}

Esta pantalla actualiza la UI usando el estado del Provider. Gracias al widget `Consumer`, se reconstruye automáticamente cuando cambia el estado en el Provider. Muestra estados de carga, error y éxito al usuario.

Manejo de Errores y Mecanismo de Reintento

El manejo de errores es muy importante en las operaciones de red. La conexión a internet puede perderse, el servidor puede devolver errores o pueden ocurrir timeouts. Creemos un mecanismo avanzado de manejo de errores para manejar estas situaciones:

import 'package:http/http.dart' as http;

class ApiException implements Exception {
  final String message;
  final int? statusCode;
  
  ApiException(this.message, [this.statusCode]);
  
  @override
  String toString() => message;
}

class ErrorHandler {
  static ApiException handleError(dynamic error) {
    if (error is http.ClientException) {
      return ApiException('No hay conexión a internet. Por favor verifica tu conexión.');
    }
    
    if (error is http.Response) {
      switch (error.statusCode) {
        case 400:
          return ApiException('Solicitud inválida', 400);
        case 401:
          return ApiException('Error de autorización', 401);
        case 403:
          return ApiException('Acceso denegado', 403);
        case 404:
          return ApiException('Recurso no encontrado', 404);
        case 500:
          return ApiException('Error del servidor', 500);
        default:
          return ApiException('Error desconocido: ${error.statusCode}', error.statusCode);
      }
    }
    
    return ApiException('Error inesperado: $error');
  }
  
  static String getErrorMessage(dynamic error) {
    if (error is ApiException) {
      return error.message;
    }
    return 'Ocurrió un error: $error';
  }
}

La clase manejadora de errores captura diferentes tipos de errores y devuelve mensajes amigables para el usuario. Esto permite mostrar mensajes de error más comprensibles a los usuarios.

Interceptor y Gestión de URL Base

Para un enfoque más profesional, es útil gestionar las solicitudes HTTP desde un lugar central y agregar interceptores. Esto se puede usar para agregar tokens de autenticación, realizar registro y gestionar la URL base:

import 'dart:convert';
import 'package:http/http.dart' as http;
import '../utils/error_handler.dart';

class HttpClient {
  final String baseUrl;
  final Map<String, String> defaultHeaders;
  
  HttpClient({
    required this.baseUrl,
    Map<String, String>? headers,
  }) : defaultHeaders = headers ?? {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
        };
  
  // Agregar token
  void setAuthToken(String token) {
    defaultHeaders['Authorization'] = 'Bearer $token';
  }
  
  // Remover token
  void removeAuthToken() {
    defaultHeaders.remove('Authorization');
  }
  
  // Solicitud GET
  Future<http.Response> get(
    String endpoint, {
    Map<String, String>? headers,
    Map<String, dynamic>? queryParameters,
  }) async {
    try {
      var uri = Uri.parse('$baseUrl$endpoint');
      
      // Agregar parámetros de consulta
      if (queryParameters != null) {
        uri = uri.replace(queryParameters: queryParameters.map(
          (key, value) => MapEntry(key, value.toString()),
        ));
      }
      
      final response = await http.get(
        uri,
        headers: {...defaultHeaders, ...?headers},
      ).timeout(
        const Duration(seconds: 30),
        onTimeout: () {
          throw ApiException('La solicitud expiró');
        },
      );
      
      _handleResponse(response);
      return response;
    } catch (e) {
      throw ErrorHandler.handleError(e);
    }
  }
  
  // Solicitud POST
  Future<http.Response> post(
    String endpoint, {
    Map<String, String>? headers,
    Object? body,
  }) async {
    try {
      final response = await http.post(
        Uri.parse('$baseUrl$endpoint'),
        headers: {...defaultHeaders, ...?headers},
        body: body is String ? body : json.encode(body),
      ).timeout(
        const Duration(seconds: 30),
        onTimeout: () {
          throw ApiException('La solicitud expiró');
        },
      );
      
      _handleResponse(response);
      return response;
    } catch (e) {
      throw ErrorHandler.handleError(e);
    }
  }
  
  // Verificación de respuesta
  void _handleResponse(http.Response response) {
    if (response.statusCode >= 400) {
      throw ErrorHandler.handleError(response);
    }
  }
}

Esta clase HttpClient gestiona todas las solicitudes HTTP desde un lugar central. Agrega automáticamente tokens de autenticación, maneja timeouts y gestiona errores.

Caché y Soporte Offline

Podemos agregar un mecanismo de caché para que la aplicación pueda funcionar offline. Esto almacena datos previamente cargados y los muestra cuando no hay conexión a internet:

import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:shared_preferences/shared_preferences.dart';

class CacheService {
  static const String _cachePrefix = 'api_cache_';
  static const Duration defaultCacheDuration = Duration(hours: 1);
  
  // Cachear datos
  static Future<void> cacheData(
    String key,
    dynamic data, {
    Duration? duration,
  }) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final cacheData = {
        'data': data,
        'timestamp': DateTime.now().millisecondsSinceEpoch,
        'expiresAt': DateTime.now()
            .add(duration ?? defaultCacheDuration)
            .millisecondsSinceEpoch,
      };
      
      await prefs.setString(
        '$_cachePrefix$key',
        json.encode(cacheData),
      );
    } catch (e) {
      debugPrint('Cache error: $e');
    }
  }
  
  // Obtener datos del caché
  static Future<dynamic> getCachedData(String key) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final cachedString = prefs.getString('$_cachePrefix$key');
      
      if (cachedString == null) return null;
      
      final cacheData = json.decode(cachedString) as Map<String, dynamic>;
      final expiresAt = cacheData['expiresAt'] as int;
      
      // Verificar si el caché expiró
      if (DateTime.now().millisecondsSinceEpoch > expiresAt) {
        await prefs.remove('$_cachePrefix$key');
        return null;
      }
      
      return cacheData['data'];
    } catch (e) {
      debugPrint('Cache read error: $e');
      return null;
    }
  }
  
  // Limpiar caché
  static Future<void> clearCache(String? key) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      if (key != null) {
        await prefs.remove('$_cachePrefix$key');
      } else {
        // Limpiar todo el caché
        final keys = prefs.getKeys();
        for (final k in keys) {
          if (k.startsWith(_cachePrefix)) {
            await prefs.remove(k);
          }
        }
      }
    } catch (e) {
      debugPrint('Cache clear error: $e');
    }
  }
}

El servicio de caché almacena datos en el dispositivo usando SharedPreferences. Esto permite mostrar datos previamente cargados incluso cuando la aplicación está offline.

Mejores Prácticas y Recomendaciones

1. Variables de Entorno

Es importante almacenar las URLs de API y otras configuraciones como variables de entorno. Esto permite cambiar fácilmente entre entornos de desarrollo y producción.

class AppConfig {
  static const String apiBaseUrl = String.fromEnvironment(
    'API_BASE_URL',
    defaultValue: 'https://api.example.com',
  );
  
  static const bool isProduction = bool.fromEnvironment('dart.vm.product');
  
  static String get apiUrl => isProduction 
    ? 'https://api.production.com'
    : 'https://api.staging.com';
}

2. Mecanismo de Reintento

Agregar un mecanismo de reintento automático para errores de red mejora la experiencia del usuario. Es especialmente útil para problemas de red temporales.

import 'dart:async';
import 'dart:math';

class RetryHelper {
  static Future<T> retry<T>({
    required Future<T> Function() action,
    int maxRetries = 3,
    Duration delay = const Duration(seconds: 1),
  }) async {
    int attempt = 0;
    
    while (attempt < maxRetries) {
      try {
        return await action();
      } catch (e) {
        attempt++;
        if (attempt >= maxRetries) {
          rethrow;
        }
        
        // Exponential backoff
        final waitTime = delay * pow(2, attempt - 1);
        await Future.delayed(waitTime);
      }
    }
    
    throw Exception('Max retries reached');
  }
}

3. Estados de Carga

Es importante mostrar siempre los estados de carga a los usuarios. Esto indica que la aplicación está funcionando y que se están cargando datos.

Conclusión

La integración de API en Flutter es bastante fácil con las herramientas y enfoques correctos. Lo que aprendimos en este artículo:

• Puedes hacer solicitudes GET, POST, PUT, DELETE con el paquete HTTP • Puedes hacer gestión de datos type-safe con clases modelo • Puedes hacer gestión de estado con Provider • Puedes agregar mecanismos de manejo de errores y reintentos • Puedes proporcionar soporte offline con caché

Al usar estas estructuras, puedes crear integraciones de API confiables y fáciles de usar. Recuerda que cada proyecto tiene necesidades diferentes, por lo que es posible que necesites personalizar estas estructuras según tu proyecto.

Recursos Adicionales

Para más información, puedes consultar estos recursos:

• Paquete HTTP de Flutter: https://pub.dev/packages/http • Paquete Provider: https://pub.dev/packages/provider • Serialización JSON: https://flutter.dev/docs/development/data-and-backend/json