Solicitudes HTTP en Flutter
Esta sección explicará cómo realizar solicitudes de red HTTP en aplicaciones Flutter, incluyendo solicitudes GET, POST y procesamiento de datos JSON.
Añadir la dependencia HTTP
Añade el paquete http en pubspec.yaml:
dependencies: http: ^1.0.0
Luego ejecuta:
$ flutter pub get
Enviar solicitud GET
Ejemplo: Solicitud GET
import 'dart:convert';
import 'package:http/http.dart' as http;
// Solicitud GET simple
Future<void> fetchData() async {
final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts/1'));
if (response.statusCode == 200) {
// Analizar datos JSON
final data = jsonDecode(response.body);
print('Título: ${data['title']}');
} else {
print('Solicitud fallida: ${response.statusCode}');
}
}
// Solicitud GET con parámetros
Future<void> searchData(String query) async {
final uri = Uri.parse('https://api.example.com/search')
.replace(queryParameters: {'q': query, 'page': '1'});
final response = await http.get(uri);
if (response.statusCode == 200) {
final data = jsonDecode(response.body);
print('Resultado: $data');
}
}
import 'package:http/http.dart' as http;
// Solicitud GET simple
Future<void> fetchData() async {
final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts/1'));
if (response.statusCode == 200) {
// Analizar datos JSON
final data = jsonDecode(response.body);
print('Título: ${data['title']}');
} else {
print('Solicitud fallida: ${response.statusCode}');
}
}
// Solicitud GET con parámetros
Future<void> searchData(String query) async {
final uri = Uri.parse('https://api.example.com/search')
.replace(queryParameters: {'q': query, 'page': '1'});
final response = await http.get(uri);
if (response.statusCode == 200) {
final data = jsonDecode(response.body);
print('Resultado: $data');
}
}
Enviar solicitud POST
Ejemplo: Solicitud POST
import 'dart:convert';
import 'package:http/http.dart' as http;
// Solicitud POST - Enviar datos JSON
Future<void> postData() async {
final uri = Uri.parse('https://jsonplaceholder.typicode.com/posts');
final response = await http.post(
uri,
headers: {
'Content-Type': 'application/json', // Configurar los encabezados de la solicitud
},
body: jsonEncode({ // Convertir objeto Dart a cadena JSON
'title': 'Tutorial de Flutter',
'body': 'Aprende solicitudes de red en Flutter',
'userId': 1,
}),
);
if (response.statusCode == 201) {
final data = jsonDecode(response.body);
print('Creación exitosa: $data');
} else {
print('Solicitud fallida: ${response.statusCode}');
}
}
// Solicitud POST - Enviar datos de formulario
Future<void> postFormData() async {
final uri = Uri.parse('https://example.com/api/login');
final response = await http.post(
uri,
body: {
'username': 'admin',
'password': '123456',
},
);
print('Respuesta: ${response.body}');
}
import 'package:http/http.dart' as http;
// Solicitud POST - Enviar datos JSON
Future<void> postData() async {
final uri = Uri.parse('https://jsonplaceholder.typicode.com/posts');
final response = await http.post(
uri,
headers: {
'Content-Type': 'application/json', // Configurar los encabezados de la solicitud
},
body: jsonEncode({ // Convertir objeto Dart a cadena JSON
'title': 'Tutorial de Flutter',
'body': 'Aprende solicitudes de red en Flutter',
'userId': 1,
}),
);
if (response.statusCode == 201) {
final data = jsonDecode(response.body);
print('Creación exitosa: $data');
} else {
print('Solicitud fallida: ${response.statusCode}');
}
}
// Solicitud POST - Enviar datos de formulario
Future<void> postFormData() async {
final uri = Uri.parse('https://example.com/api/login');
final response = await http.post(
uri,
body: {
'username': 'admin',
'password': '123456',
},
);
print('Respuesta: ${response.body}');
}
Procesar datos JSON
Ejemplo: Parseo de JSON
import 'dart:convert';
// Definir el modelo de datos
class Article {
final int id;
final String title;
final String body;
final User user;
Article({
required this.id,
required this.title,
required this.body,
required this.user,
});
// Analizar desde JSON
factory Article.fromJson(Map<String, dynamic> json) {
return Article(
id: json['id'],
title: json['title'],
body: json['body'],
user: User.fromJson(json['user']),
);
}
// Convertir a JSON
Map<String, dynamic> toJson() {
return {
'id': id,
'title': title,
'body': body,
'user': user.toJson(),
};
}
}
class User {
final int id;
final String name;
User({required this.id, required this.name});
factory User.fromJson(Map<String, dynamic> json) {
return User(id: json['id'], name: json['name']);
}
Map<String, dynamic> toJson() {
return {'id': id, 'name': name};
}
}
// Ejemplo de uso
void parseJson() {
final jsonString = '''
{
"id": 1,
"title": "Tutorial de Flutter",
"body": "Aprende Flutter",
"user": {"id": 1, "name": "Juan"}
}
''';
// Analizar cadena JSON
final Map<String, dynamic> json = jsonDecode(jsonString);
final article = Article.fromJson(json);
print('ID del artículo: ${article.id}');
print('Autor: ${article.user.name}');
}
// Definir el modelo de datos
class Article {
final int id;
final String title;
final String body;
final User user;
Article({
required this.id,
required this.title,
required this.body,
required this.user,
});
// Analizar desde JSON
factory Article.fromJson(Map<String, dynamic> json) {
return Article(
id: json['id'],
title: json['title'],
body: json['body'],
user: User.fromJson(json['user']),
);
}
// Convertir a JSON
Map<String, dynamic> toJson() {
return {
'id': id,
'title': title,
'body': body,
'user': user.toJson(),
};
}
}
class User {
final int id;
final String name;
User({required this.id, required this.name});
factory User.fromJson(Map<String, dynamic> json) {
return User(id: json['id'], name: json['name']);
}
Map<String, dynamic> toJson() {
return {'id': id, 'name': name};
}
}
// Ejemplo de uso
void parseJson() {
final jsonString = '''
{
"id": 1,
"title": "Tutorial de Flutter",
"body": "Aprende Flutter",
"user": {"id": 1, "name": "Juan"}
}
''';
// Analizar cadena JSON
final Map<String, dynamic> json = jsonDecode(jsonString);
final article = Article.fromJson(json);
print('ID del artículo: ${article.id}');
print('Autor: ${article.user.name}');
}
Manejo de errores
Ejemplo: Ejemplo completo de solicitud de red
import 'dart:convert';
import 'package:http/http.dart' as http;
class ApiService {
// URL base
static const String baseUrl = 'https://jsonplaceholder.typicode.com';
// Método de solicitud GET genérico
static Future<dynamic> get(String endpoint) async {
try {
final response = await http.get(
Uri.parse('$baseUrl/$endpoint'),
);
return _handleResponse(response);
} catch (e) {
throw ApiException('Error de red: $e');
}
}
// Método de solicitud POST genérico
static Future<dynamic> post(
String endpoint,
Map<String, dynamic> data,
) async {
try {
final response = await http.post(
Uri.parse('$baseUrl/$endpoint'),
headers: {'Content-Type': 'application/json'},
body: jsonEncode(data),
);
return _handleResponse(response);
} catch (e) {
throw ApiException('Error de red: $e');
}
}
// Procesar la respuesta
static dynamic _handleResponse(http.Response response) {
if (response.statusCode >= 200 && response.statusCode < 300) {
// Respuesta exitosa
if (response.body.isEmpty) {
return null;
}
return jsonDecode(response.body);
} else if (response.statusCode == 404) {
throw ApiException('Recurso no encontrado', statusCode: 404);
} else if (response.statusCode >= 500) {
throw ApiException('Error del servidor', statusCode: response.statusCode);
} else {
throw ApiException(
'Solicitud fallida',
statusCode: response.statusCode,
);
}
}
}
// Clase de excepción personalizada
class ApiException implements Exception {
final String message;
final int? statusCode;
ApiException(this.message, {this.statusCode});
@override
String toString() => 'ApiException: $message (status: $statusCode)';
}
// Ejemplo de uso
Future<void> fetchArticles() async {
try {
final articles = await ApiService.get('posts');
print('Se obtuvieron ${articles.length} artículos');
} on ApiException catch (e) {
print('Error de API: $e');
}
}
import 'package:http/http.dart' as http;
class ApiService {
// URL base
static const String baseUrl = 'https://jsonplaceholder.typicode.com';
// Método de solicitud GET genérico
static Future<dynamic> get(String endpoint) async {
try {
final response = await http.get(
Uri.parse('$baseUrl/$endpoint'),
);
return _handleResponse(response);
} catch (e) {
throw ApiException('Error de red: $e');
}
}
// Método de solicitud POST genérico
static Future<dynamic> post(
String endpoint,
Map<String, dynamic> data,
) async {
try {
final response = await http.post(
Uri.parse('$baseUrl/$endpoint'),
headers: {'Content-Type': 'application/json'},
body: jsonEncode(data),
);
return _handleResponse(response);
} catch (e) {
throw ApiException('Error de red: $e');
}
}
// Procesar la respuesta
static dynamic _handleResponse(http.Response response) {
if (response.statusCode >= 200 && response.statusCode < 300) {
// Respuesta exitosa
if (response.body.isEmpty) {
return null;
}
return jsonDecode(response.body);
} else if (response.statusCode == 404) {
throw ApiException('Recurso no encontrado', statusCode: 404);
} else if (response.statusCode >= 500) {
throw ApiException('Error del servidor', statusCode: response.statusCode);
} else {
throw ApiException(
'Solicitud fallida',
statusCode: response.statusCode,
);
}
}
}
// Clase de excepción personalizada
class ApiException implements Exception {
final String message;
final int? statusCode;
ApiException(this.message, {this.statusCode});
@override
String toString() => 'ApiException: $message (status: $statusCode)';
}
// Ejemplo de uso
Future<void> fetchArticles() async {
try {
final articles = await ApiService.get('posts');
print('Se obtuvieron ${articles.length} artículos');
} on ApiException catch (e) {
print('Error de API: $e');
}
}
Otras extensionesEn aplicaciones reales, se recomienda encapsular las solicitudes de red en una clase de servicio para manejar de manera unificada los errores, el estado de carga y la lógica de caché.