What is an API?
An API is a web address that returns data instead of a web page. Most apps get their data (products, posts, weather) from such addresses. The data usually comes as JSON, a text format of keys and values.
json
{
"id": 1,
"title": "Learn Flutter",
"completed": false
}
Install the Package
bash
flutter pub add http
Android and macOS Permissions
- Android: add
<uses-permission android:name="android.permission.INTERNET" /> to android/app/src/main/AndroidManifest.xml. Debug builds already have it, but release builds need it.
- macOS: enable the outgoing network entitlement
com.apple.security.network.client in the entitlement files.
Step 1: Create a Model Class
We use the free test API jsonplaceholder.typicode.com.
dart
class Todo {
final int id;
final String title;
final bool completed;
const Todo({required this.id, required this.title, required this.completed});
factory Todo.fromJson(Map<String, dynamic> json) {
return Todo(
id: json['id'] as int,
title: json['title'] as String,
completed: json['completed'] as bool,
);
}
Map<String, dynamic> toJson() => {
'id': id,
'title': title,
'completed': completed,
};
}
Step 2: GET Request
dart
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=20');
final response = await http.get(uri).timeout(const Duration(seconds: 10));
if (response.statusCode == 200) {
final List<dynamic> data = jsonDecode(response.body);
return data.map((item) => Todo.fromJson(item as Map<String, dynamic>)).toList();
} else {
throw Exception('Failed to load todos (${response.statusCode})');
}
}
| Status code | Meaning |
| 200 | OK |
| 201 | Created (after POST) |
| 400 | Bad request (your data is wrong) |
| 401 / 403 | Not logged in or not allowed |
| 404 | Not found |
| 500 | Server error |
Step 3: POST Request
dart
Future<Todo> createTodo(String title) async {
final response = await http.post(
Uri.parse('https://jsonplaceholder.typicode.com/todos'),
headers: {'Content-Type': 'application/json; charset=UTF-8'},
body: jsonEncode({'title': title, 'completed': false, 'userId': 1}),
);
if (response.statusCode == 201) {
return Todo.fromJson(jsonDecode(response.body) as Map<String, dynamic>);
}
throw Exception('Failed to create todo');
}
Other methods work the same way: http.put, http.patch and http.delete. Add an Authorization header when the API needs a token.
dart
headers: {
'Authorization': 'Bearer $token',
'Accept': 'application/json',
}
Step 4: Show the Result
dart
class TodoPage extends StatefulWidget {
const TodoPage({super.key});
@override
State<TodoPage> createState() => _TodoPageState();
}
class _TodoPageState extends State<TodoPage> {
late Future<List<Todo>> _future;
@override
void initState() {
super.initState();
_future = fetchTodos(); // start once, not inside build
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Todos')),
body: FutureBuilder<List<Todo>>(
future: _future,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const Center(child: CircularProgressIndicator());
}
if (snapshot.hasError) {
return Center(child: Text('Error: ${snapshot.error}'));
}
final todos = snapshot.data!;
return ListView.builder(
itemCount: todos.length,
itemBuilder: (context, i) => CheckboxListTile(
value: todos[i].completed,
onChanged: null,
title: Text(todos[i].title),
),
);
},
),
);
}
}
Big mistake to avoid: Never call fetchTodos() directly inside build(). build runs many times, so you would send many requests. Create the Future once in initState.
Handling Errors Well
dart
try {
final todos = await fetchTodos();
} on SocketException {
// no internet
} on TimeoutException {
// too slow
} on FormatException {
// bad JSON
} catch (e) {
// anything else
}
SocketException needs import 'dart:io'; and TimeoutException needs import 'dart:async';. These are not available on the web, so use a general catch for web apps.
Security: Never put secret API keys inside your Flutter app. Anyone can extract them from the app. Keep secrets on your own server.
Conclusion
With the http package, a model class and FutureBuilder you can connect your app to any REST API. Always handle loading, error and success states.
Quick Summary: Use http.get and post with Uri.parse, decode JSON into model classes, create the Future once and handle errors.