Flutter HTTP-Anfrage

In diesem Abschnitt wird erläutert, wie HTTP-Netzwerkanfragen in Flutter-Anwendungen durchgeführt werden, einschließlich GET-, POST-Anfragen und der Verarbeitung von JSON-Daten.


HTTP-Abhängigkeit hinzufügen

Fügen Sie das Paket http in pubspec.yaml hinzu:

dependencies:
  http: ^1.0.0

Führen Sie dann aus:

$ flutter pub get

GET-Anfrage senden

Beispiel: GET-Anfrage

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

// Einfache GET-Anfrage
Future<void> fetchData() async {
  final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts/1'));

  if (response.statusCode == 200) {
    // JSON-Daten parsen
    final data = jsonDecode(response.body);
    print('Titel: ${data['title']}');
  } else {
    print('Anfrage fehlgeschlagen: ${response.statusCode}');
  }
}

// GET-Anfrage mit Parametern
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(Ergebnis: $data);
  }
}

POST-Anfrage senden

Beispiel: POST-Anfrage

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

// POST-Anfrage - JSON-Daten senden
Future<void> postData() async {
  final uri = Uri.parse('https://jsonplaceholder.typicode.com/posts');

  final response = await http.post(
    uri,
    headers: {
      'Content-Type': 'application/json',  // Anfrage-Header setzen
    },
    body: jsonEncode({  // Ein Dart-Objekt in einen JSON-String konvertieren
      'title': Flutter-Tutorial,
      'body': 'Flutter-Netzwerkanfragen lernen',
      'userId': 1,
    }),
  );

  if (response.statusCode == 201) {
    final data = jsonDecode(response.body);
    print('Erfolgreich erstellt: $data');
  } else {
    print('Anfrage fehlgeschlagen: ${response.statusCode}');
  }
}

// POST-Anfrage - Formulardaten senden
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('Antwort: ${response.body}');
}

JSON-Daten verarbeiten

Beispiel: JSON-Parsing

import 'dart:convert';

// Datenmodell definieren
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,
  });

  // Aus JSON parsen
  factory Article.fromJson(Map<String, dynamic> json) {
    return Article(
      id: json['id'],
      title: json['title'],
      body: json['body'],
      user: User.fromJson(json['user']),
    );
  }

  // In JSON konvertieren
  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};
  }
}

// Anwendungsbeispiel
void parseJson() {
  final jsonString = '''
  {
    "id": 1,
"title": "Flutter-Tutorial",
"body": "Flutter lernen",
"user": {"id": 1, "name": "Zhang San"}
  }
  '
'';

  // JSON-String parsen
  final Map<String, dynamic> json = jsonDecode(jsonString);
  final article = Article.fromJson(json);

  print('Artikel-ID: ${article.id}');
  print('Autor: ${article.user.name}');
}

Fehlerbehandlung

Beispiel: Vollständiges Beispiel für eine Netzwerkanfrage

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

class ApiService {
  // Basis-URL
  static const String baseUrl = 'https://jsonplaceholder.typicode.com';

  // Generische GET-Anfragemethode
  static Future<dynamic> get(String endpoint) async {
    try {
      final response = await http.get(
        Uri.parse('$baseUrl/$endpoint'),
      );
      return _handleResponse(response);
    } catch (e) {
      throw ApiException('Netzwerkfehler: $e');
    }
  }

  // Generische POST-Anfragemethode
  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('Netzwerkfehler: $e');
    }
  }

  // Antwort verarbeiten
  static dynamic _handleResponse(http.Response response) {
    if (response.statusCode >= 200 && .statusCode < 300) {
      // Erfolgreiche Antwort
      if (response.body.isEmpty) {
        return null;
      }
      return jsonDecode(response.body);
    } else if (response.status == 404) {
      throw ApiException(Ressource nicht gefunden, statusCode: 404);
    } else if (response.status >= 500) {
      throw ApiException('Serverfehler', statusCode: response.statusCode);
    } else {
      throw ApiException(
        'Anfrage fehlgeschlagen',
        statusCode: response.statusCode,
      );
    }
  }
}

// Benutzerdefinierte Exception-Klasse
class ApiException implements Exception {
  final String message;
  final int? statusCode;

  ApiException(this.message, {this.statusCode});

  @override
  String toString() => 'ApiException: $message (Status: $statusCode)';
}

// Anwendungsbeispiel
Future<void> fetchArticles() async {
  try {
    final articles = await ApiService.get('posts');
    print('${articles.length} Artikel abgerufen');
  } on ApiException catch (e) {
    print('API-Fehler: $e');
  }
}

In realen Anwendungen wird empfohlen, Netzwerkanfragen in Service-Klassen zu kapseln, um Fehler, Ladezustände und Caching-Logik einheitlich zu behandeln.

Weitere Erweiterungen