Flutter HTTP & JSON
Most apps talk to a server: they download a list of products, post a comment, or log a user in. The usual format for that data is JSON. In this lesson you will learn to decode and encode JSON with dart:convert, turn it into typed model classes, and fetch it over HTTP with the http package.
JSON in Dart
dart:convert has two key functions:
jsonDecode(String)turns JSON text into Dart objects: JSON objects becomeMap<String, dynamic>, arrays becomeList<dynamic>, and numbers, strings, booleans andnullmap directly.jsonEncode(Object)does the reverse.
This example runs for real:
import 'dart:convert';
void main() {
const body = '{"id": 42, "title": "Buy milk", "done": false, "tags": ["home", "shop"]}';
final data = jsonDecode(body) as Map<String, dynamic>;
print(data['title']);
print(data['tags'] is List);
print((data['tags'] as List).length);
final back = jsonEncode({'id': 1, 'ok': true, 'score': 9.5});
print(back);
}Buy milk
true
2
{"id":1,"ok":true,"score":9.5}
Model classes with fromJson / toJson
Working with data['title'] everywhere is error-prone: typos are not caught, and every value is dynamic. The common pattern is a small immutable class with a fromJson factory constructor and a toJson method.
import 'dart:convert';
class Todo {
const Todo({required this.id, required this.title, required this.done});
final int id;
final String title;
final bool done;
factory Todo.fromJson(Map<String, dynamic> json) => Todo(
id: json['id'] as int,
title: json['title'] as String,
done: json['completed'] as bool,
);
Map<String, dynamic> toJson() => {'id': id, 'title': title, 'completed': done};
@override
String toString() => '${done ? '[x]' : '[ ]'} #$id $title';
}
void main() {
const response = '''
[
{"id": 1, "title": "Learn Dart", "completed": true},
{"id": 2, "title": "Learn Flutter", "completed": false}
]''';
final todos = (jsonDecode(response) as List)
.map((e) => Todo.fromJson(e as Map<String, dynamic>))
.toList();
todos.forEach(print);
print(jsonEncode(todos.first.toJson()));
}[x] #1 Learn Dart
[ ] #2 Learn Flutter
{"id":1,"title":"Learn Dart","completed":true}
Tip: Dart 3 patterns make decoding even safer:
if (json case {'id': int id, 'title': String title}) { … }checks the shape and types in one step.
For big models, packages like json_serializable or freezed generate fromJson/toJson for you.
Fetching data with the http package
Add the package to your project:
flutter pub add httpResolving dependencies...
+ http 1.2.2
Changed 1 dependency!
Then write a function that requests a URL, checks the status code and decodes the body. This needs a real network, so it cannot run here — the output shows what you would see.
import 'dart:convert';
import 'package:http/http.dart' as http;
Future<List<Todo>> fetchTodos() async {
final uri = Uri.parse('https://jsonplaceholder.typicode.com/todos?_limit=3');
final response = await http.get(uri);
if (response.statusCode != 200) {
throw Exception('Request failed: ${response.statusCode}');
}
final list = jsonDecode(response.body) as List;
return list.map((e) => Todo.fromJson(e as Map<String, dynamic>)).toList();
}
Future<void> main() async {
final todos = await fetchTodos();
for (final t in todos) {
debugPrint(t.toString());
}
}[ ] #1 delectus aut autem
[ ] #2 quis ut nam facilis et officia qui
[ ] #3 fugiat veniam minus
Sending data uses http.post with a JSON body and a content-type header:
final response = await http.post(
Uri.parse('https://example.com/api/todos'),
headers: {'Content-Type': 'application/json'},
body: jsonEncode(const Todo(id: 0, title: 'New task', done: false).toJson()),
);
debugPrint('Status: ${response.statusCode}');Status: 201
Showing it in the UI
Combine fetchTodos() with the FutureBuilder from the previous lesson: store the future in your State, show a spinner while waiting, an error text with a retry button on failure, and a ListView of todos on success.
// Inside a State class
late final Future<List<Todo>> _todos = fetchTodos();
@override
Widget build(BuildContext context) {
return FutureBuilder<List<Todo>>(
future: _todos,
builder: (context, snapshot) {
if (snapshot.hasError) return Center(child: Text('${snapshot.error}'));
if (!snapshot.hasData) return const Center(child: CircularProgressIndicator());
return ListView(
children: [
for (final t in snapshot.data!)
CheckboxListTile(value: t.done, onChanged: null, title: Text(t.title)),
],
);
},
);
}Platform notes
| Platform | What to check |
|---|---|
| Android | Release builds need <uses-permission android:name="android.permission.INTERNET"/> in AndroidManifest.xml |
| macOS | Enable the Outgoing Connections entitlement |
| Web | The server must allow your origin (CORS) |
Note: Never block the UI waiting for a response — always
awaitinside anasyncfunction, and handle errors and timeouts (http.get(uri).timeout(const Duration(seconds: 10))).
Test yourself
What type does jsonDecode return for a JSON object like {"a": 1}?
- String
- List<dynamic>
- Map<String, dynamic>
- Object with fields
Which kind of constructor is commonly used for Todo.fromJson?
- A const constructor
- A factory constructor
- A private constructor
- A redirecting operator
What should you check before decoding an HTTP response body?
- The response's statusCode
- The device battery
- That the widget is stateless
- Nothing