Learn/Async UI & APIs/HTTP Requests

HTTP Requests

Make API calls with the http package

6 min~5 min read+35 FX

You can read this lesson publicly. Sign in to unlock exercises, quiz, and FX progress tracking.

Table of Contents

  1. 1. Model Class with JSON
  2. 2. Network Layer Boundaries
  3. 3. This Lesson In Simple Words
  4. 4. Your level focus
  5. 5. One practical habit
  6. 6. Deep Understanding Guide
  7. 7. Why this lesson matters
  8. 8. Study flow for better retention
  9. 9. Quick Glossary

Having trouble? AI is here to help

Ask context-aware questions about this lesson. Free plan: 5 questions/day. Upgrade to Premium for higher daily limits.

Use the AI button at the bottom of the screen

Making HTTP Requests

Most Flutter apps need to fetch data from a server or send data to one. The http package is the standard way to make network requests in Dart. It supports GET, POST, PUT, DELETE, and other HTTP methods. Every request returns a Response object that contains the status code, headers, and body. You check the status code to determine if the request succeeded, then parse the body to extract useful data.

yaml
1# Add to pubspec.yaml
2dependencies:
3 http: ^1.1.0
dart
1import 'dart:convert';
2import 'package:http/http.dart' as http;
3
4// GET request
5Future<User> fetchUser(int id) async {
6 final response = await http.get(
7 Uri.parse('https://api.example.com/users/$id'),
8 headers: {'Authorization': 'Bearer token'},
9 );
10
11 if (response.statusCode == 200) {
12 final json = jsonDecode(response.body);
13 return User.fromJson(json);
14 } else {
15 throw Exception('Failed to load user');
16 }
17}
18
19// POST request
20Future<User> createUser(String name, String email) async {
21 final response = await http.post(
22 Uri.parse('https://api.example.com/users'),
23 headers: {'Content-Type': 'application/json'},
24 body: jsonEncode({
25 'name': name,
26 'email': email,
27 }),
28 );
29
30 if (response.statusCode == 201) {
31 return User.fromJson(jsonDecode(response.body));
32 } else {
33 throw Exception('Failed to create user');
34 }
35}

Model Class with JSON

Raw JSON data arrives as a Map of strings and dynamic values, which is error-prone to work with directly. A model class gives you type safety, autocomplete in your IDE, and a single place to define how your data is structured. Every model needs a fromJson factory constructor to parse incoming data and a toJson method to send data back to the server.

dart
1class User {
2 final int id;
3 final String name;
4 final String email;
5
6 User({required this.id, required this.name, required this.email});
7
8 // From JSON
9 factory User.fromJson(Map<String, dynamic> json) {
10 return User(
11 id: json['id'],
12 name: json['name'],
13 email: json['email'],
14 );
15 }
16
17 // To JSON
18 Map<String, dynamic> toJson() {
19 return {
20 'id': id,
21 'name': name,
22 'email': email,
23 };
24 }
25}

Network Layer Boundaries

Separate responsibilities clearly:

  • service layer handles HTTP and status code checks
  • model layer handles parsing and serialization
  • UI layer handles loading, success, and error states

This separation prevents network logic from leaking into widgets and simplifies testing.

HTTP Reliability Checklist

  • Status code handling is explicit for success and failure.
  • Request and response models are strongly typed.
  • Timeout and network exceptions are handled.
  • Sensitive headers and tokens are managed securely.

This Lesson In Simple Words

Make API calls with the http package. Networking lessons teach your app how to request, store, and display remote data safely.

Your level focus

Connect each concept to real app features you can build.

One practical habit

Always model loading, success, empty, and error states before hooking the UI.

Deep Understanding Guide

Why this lesson matters

Most production bugs happen at data boundaries: slow networks, bad payloads, and error states.

Study flow for better retention

  1. Map the lesson to one screen, one user action, and one expected output.
  2. Treat every network call as unreliable and design graceful fallback behavior.
  3. If you can choose between two approaches and explain why, you are improving.

Common Mistakes To Avoid

  • Triggering API calls inside build methods and causing duplicate requests.
  • Assuming response fields always exist without null checks or parsing safeguards.
  • Displaying backend errors directly to users without safe messaging.
  • Skipping retry and offline handling for key user actions.

Practice Sprint (15-25 Minutes)

  • Before running sample code, predict output and behavior in one sentence.
  • Implement one repository with timeout, retry, and typed parsing.
  • Add pull-to-refresh and compare stale vs fresh data behavior.
  • Create a clear UI state for empty list and network failure cases.
  • Complete the required exercises without using hints on the first attempt.
  • Answer this question out loud before checking quiz options: "What function converts JSON string to Map?".

Quick Glossary

  • widget: A reusable UI building block in Flutter.
  • state: Data that can change and update what the user sees.
  • const: A compile-time constant that can reduce rebuild work.

Code Comprehension Drill

  • State the purpose of the code block in one line before reading details.
  • Mark inputs, state changes, and final output.
  • Change one small value and predict what should happen before running.
  • Run again and compare your prediction with actual behavior.

Lesson Completion Checklist

  • I can explain "HTTP Requests" in simple words without reading notes.
  • I can describe one real app situation where this concept is required.
  • I know at least one mistake to avoid: Triggering API calls inside build methods and causing duplicate requests.
  • I can modify one code sample and correctly predict the behavior change.
  • I can finish required exercises with understanding, not trial-and-error guesses.

Frequently Asked Questions

What function converts JSON string to Map?

jsonDecode() from dart:convert parses JSON strings into Dart objects.

What HTTP status code indicates successful resource creation?

201 Created indicates the request succeeded and a new resource was created.

What does jsonEncode() do?

jsonEncode converts a Dart Map or List to a JSON string for sending in HTTP request bodies.

What is the purpose of factory User.fromJson()?

fromJson factory constructor parses a Map<String, dynamic> (from JSON) into a typed Dart object.

Suggest Improvement

Something seems incorrect, unclear, or missing? Let us know.

About The Author

FlutterCraft editorial lessons are reviewed by experienced Flutter developers and updated to stay aligned with modern Flutter and Dart best practices.

Reference docs: Flutter Documentation, Dart Language Tour, and official package documentation where relevant.

Sign in to continue with exercises and quiz for this lesson.

Sign In to Continue