Sub topic 1
How REST and HTTP work
Prerequisites
This chapter assumes you know Dart classes, null safety, named parameters, and async/await with Future. You should also have a Flutter project open and know how to add a package to pubspec.yaml.
How REST and HTTP work
REST is a style for designing web APIs. A server exposes resources, such as posts or users, at URLs. HTTP is the protocol that a client uses to read and change those resources. Each exchange is one request followed by one response.
A request has a method, a URL, headers, and an optional body. The common methods are GET (read), POST (create), PUT and PATCH (update), and DELETE (remove). The response has a status code, headers, and usually a JSON body. Codes in the 200 range mean success, 4xx means the client sent a bad request, and 5xx means the server failed.
Allowing network access on each platform
Each platform has its own permission rules.
- Android: Add
<uses-permission android:name="android.permission.INTERNET"/>toandroid/app/src/main/AndroidManifest.xml, above the<application>tag. - macOS: Sandboxed apps need
com.apple.security.network.clientset totruein bothmacos/Runner/DebugProfile.entitlementsandmacos/Runner/Release.entitlements. - iOS: HTTPS works without changes under App Transport Security. Plain
http://URLs are blocked unless you add an exception, so prefer HTTPS. - Web: The browser enforces CORS. The server must allow your app's origin, and no Flutter setting can change that.
Your first GET request with the http package
Add the package with flutter pub add http. The following program fetches one post and prints the raw body.
import 'package:http/http.dart' as http;
Future<void> main() async {
final uri = Uri.https('jsonplaceholder.typicode.com', '/posts/1');
final response = await http.get(uri);
if (response.statusCode == 200) {
print(response.body);
} else {
print('Request failed: ${response.statusCode}');
}
}Turning JSON into Dart models
jsonDecode turns the response text into a Map<String, dynamic>, which is untyped. A model class gives each field a fixed Dart type, so mistakes show up early.
import 'dart:convert';
import 'package:http/http.dart' as http;
class Post {
const Post({required this.id, required this.title});
factory Post.fromJson(Map<String, dynamic> json) {
return Post(id: json['id'] as int, title: json['title'] as String);
}
final int id;
final String title;
}
Future<Post> fetchPost(int id) async {
final uri = Uri.https('jsonplaceholder.typicode.com', '/posts/$id');
final response = await http.get(uri);
if (response.statusCode != 200) {
throw Exception('Failed to load post: ${response.statusCode}');
}
final json = jsonDecode(response.body) as Map<String, dynamic>;
return Post.fromJson(json);
}
Future<void> main() async {
final post = await fetchPost(1);
print('${post.id}: ${post.title}');
}Exercise
If the server returns "id" as the string "1" instead of the number 1, what happens when fromJson runs?
Show answer
The cast json['id'] as int throws a TypeError during parsing. The error appears at the model boundary, not later in the UI.