Flutter Mobile Development · Pelajaran

Permintaan HTTP dan JSON

Pelajari cara membuat permintaan HTTP GET, POST, PUT, dan DELETE ke API REST serta mengurai respons JSON menjadi objek Dart.

Pelajaran 2 dari 412 langkah

Permintaan HTTP dan JSON adalah pelajaran Flutter Mobile Development gratis di CoddyKit. Ini adalah pelajaran 2 dari 4. Kamu bisa membaca pelajaran lengkapnya di bawah secara gratis — lalu praktikkan langsung di browser dengan editor kode bawaan dan tutor AI 24/7. Ini adalah bagian dari jalur belajar Flutter Mobile Development, dan progresmu tersinkronisasi di web dan aplikasi CoddyKit. Kursus Flutter Mobile Development mencakup 4 pelajaran total.

Bagian dari pelajaran ini belum diterjemahkan dan ditampilkan dalam bahasa Inggris.

Connect to the Web!

Modern mobile apps constantly interact with the internet to fetch and send data. This is often done using HTTP requests to communicate with web services, also known as APIs (Application Programming Interfaces).

APIs provide a way for different software systems to talk to each other. For example, a weather app uses an API to get the latest forecast.

Get the `http` Package

In Flutter and Dart, the easiest way to make HTTP requests is by using the official http package. First, you need to add it to your project's pubspec.yaml file:

dependencies:
  flutter:
    sdk: flutter
  http: ^1.2.0 # Add this line

Making a GET Request

After adding the package, import it into your Dart file. The most common request is GET, used to retrieve data from a server. Let's fetch some dummy post data from a public API:

import 'package:http/http.dart' as http;
import 'dart:convert'; // Needed for JSON

void main() async {
  var url = Uri.parse('https://jsonplaceholder.typicode.com/posts/1');
  var response = await http.get(url);

  if (response.statusCode == 200) {
    print('Response body: ${response.body}');
  } else {
    print('Request failed with status: ${response.statusCode}.');
  }
}

What is JSON?

Most web APIs return data in JSON (JavaScript Object Notation) format. It's a lightweight, human-readable way to organize data.

JSON data looks like key-value pairs, similar to Dart maps. Here's what our previous GET request might return:

{
  "userId": 1,
  "id": 1,
  "title": "sunt aut facere...",
  "body": "quia et suscipit..."
}

Parsing JSON to Dart

To work with JSON data in Dart, we need to decode it. Dart's dart:convert library provides the jsonDecode() function, which converts a JSON string into a Dart Map.

Let's update our GET example to parse the response:

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

void main() async {
  var url = Uri.parse('https://jsonplaceholder.typicode.com/posts/1');
  var response = await http.get(url);

  if (response.statusCode == 200) {
    var jsonBody = jsonDecode(response.body);
    print('User ID: ${jsonBody['userId']}');
    print('Title: ${jsonBody['title']}');
  } else {
    print('Request failed with status: ${response.statusCode}.');
  }
}

Structured Data with Models

While using Map is okay for simple cases, creating a dedicated Dart model class for your JSON data offers better type safety and code readability.

A common pattern is to have a factory constructor that takes a JSON map and creates an instance of your model.

class Post {
  final int userId;
  final int id;
  final String title;
  final String body;

  Post({required this.userId, required this.id, required this.title, required this.body});

  factory Post.fromJson(Map<String, dynamic> json) {
    return Post(
      userId: json['userId'] as int,
      id: json['id'] as int,
      title: json['title'] as String,
      body: json['body'] as String,
    );
  }
}

Fetching Data into a Model

Now, let's combine our GET request, JSON decoding, and the Post model to fetch a post and convert it into a strongly-typed Dart object. This makes accessing data much safer and clearer!

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

class Post {
  final int userId;
  final int id;
  final String title;
  final String body;

  Post({required this.userId, required this.id, required this.title, required this.body});

  factory Post.fromJson(Map<String, dynamic> json) {
    return Post(
      userId: json['userId'] as int,
      id: json['id'] as int,
      title: json['title'] as String,
      body: json['body'] as String,
    );
  }
}

void main() async {
  var url = Uri.parse('https://jsonplaceholder.typicode.com/posts/1');
  var response = await http.get(url);

  if (response.statusCode == 200) {
    var jsonBody = jsonDecode(response.body);
    Post post = Post.fromJson(jsonBody);
    print('Fetched Post ID: ${post.id}');
    print('Post Title: ${post.title}');
  } else {
    print('Failed to load post: ${response.statusCode}.');
  }
}

Sending Data with POST

To send new data to a server, you typically use a POST request. This involves providing a request body, usually in JSON format. Remember to set the 'Content-Type' header!

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

void main() async {
  var url = Uri.parse('https://jsonplaceholder.typicode.com/posts');
  var response = await http.post(
    url,
    headers: <String, String>{
      'Content-Type': 'application/json; charset=UTF-8',
    },
    body: jsonEncode(<String, String>{
      'title': 'foo',
      'body': 'bar',
      'userId': '1',
    }),
  );

  if (response.statusCode == 201) { // 201 Created
    print('Created Post: ${response.body}');
  } else {
    print('Failed to create post: ${response.statusCode}.');
  }
}

Updating & Deleting Data

Besides GET and POST, you'll also encounter PUT and DELETE requests:

  • PUT: Used to update an existing resource on the server. Similar to POST, it typically includes a request body.
  • DELETE: Used to remove a resource from the server. It usually doesn't require a request body.

The http package provides http.put() and http.delete() functions, used similarly to http.post() and http.get() respectively.

Robust Request Handling

Network requests can fail for many reasons (no internet, server down, invalid data). Always prepare for these scenarios:

  • Use try-catch for network-related exceptions (e.g., SocketException).
  • Check response.statusCode to understand the server's reply (e.g., 200 OK, 404 Not Found, 500 Server Error).

This ensures your app remains stable even when things go wrong.

HTTP Request Check

Which HTTP method(s) are typically used to send new data to a server and retrieve existing data from a server, respectively?

Recap: HTTP & JSON

Great job! You've learned the fundamentals of making HTTP requests and handling JSON data:

  • The http package is essential for network calls.
  • GET retrieves data, POST sends new data, PUT updates, and DELETE removes data.
  • JSON is the standard format for API data.
  • Use dart:convert to jsonDecode responses and jsonEncode request bodies.
  • Dart model classes improve type safety and organization.

Next, you'll dive deeper into handling errors robustly in asynchronous operations!

Gratis untuk memulai

Belajar Dart dengan tutor AI — gratis

Tulis dan jalankan kode asli di browser kamu, dapatkan bantuan instan dari tutor AI 24/7, dan lanjutkan di mana kamu tinggalkan di web atau aplikasi.

Kursus
22
Pelajaran
88

Pertanyaan yang Sering Diajukan

Apakah pelajaran “Permintaan HTTP dan JSON” gratis?

Ya — teks lengkap “Permintaan HTTP dan JSON” gratis dibaca di sini di web. Untuk praktiknya secara interaktif (editor kode bawaan dan tutor AI 24/7) dan buka sisa kursus Flutter Mobile Development, upgrade ke CoddyKit PRO. Kursus Flutter Mobile Development mencakup 4 pelajaran total.

Apa yang akan aku pelajari di “Permintaan HTTP dan JSON”?

Pelajari cara membuat permintaan HTTP GET, POST, PUT, dan DELETE ke API REST serta mengurai respons JSON menjadi objek Dart. Kamu berlatih Flutter Mobile Development dengan kode praktik yang langsung kamu jalankan di browser, dan tutor AI 24/7 menjawab pertanyaanmu saat kamu mengerjakan pelajaran ini.

Apakah aku perlu pengalaman untuk memulai Flutter Mobile Development?

Tidak diperlukan pengalaman sebelumnya. Flutter Mobile Development di CoddyKit dirancang untuk pemula hingga pelajar tingkat lanjut, jadi kamu bisa memulai di sini atau dari awal dan belajar sesuai kecepatan kamu sendiri. Ini adalah pelajaran 2 dari 4.

Berapa lama pelajaran “Permintaan HTTP dan JSON” memakan waktu?

Sebagian besar pelajaran CoddyKit memakan waktu sekitar 5–10 menit. Setiap pelajaran ringkas dan interaktif, jadi kamu membuat kemajuan stabil dan melanjutkan dari tempat kamu tinggalkan di web dan aplikasi.

Bisakah aku menulis dan menjalankan kode dalam pelajaran Flutter Mobile Development ini?

Ya. Setiap pelajaran Flutter Mobile Development menyertakan editor kode bawaan, jadi kamu menulis dan menjalankan kode nyata langsung di browser dan mendapatkan umpan balik AI instan — tidak diperlukan penyiapan lokal.

Semua pelajaran dalam kursus ini

  1. Future dan Async/Await
  2. Permintaan HTTP dan JSON
  3. Penanganan Error dalam Operasi Asinkron
  4. Stream dan Data Reaktif
← Kembali ke Flutter Mobile Development