Flutter API Call with http: solved exercise
If you are looking for Flutter API call with http, this solved exercise gives you a practical implementation pattern you can reuse in real projects.
Problem statement
Build a screen with:
- fetch data from a public REST endpoint
- decode JSON payload
- render list results safely
Flutter solution
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void main() => runApp(const MaterialApp(home: ApiPage()));
class ApiPage extends StatefulWidget {
const ApiPage({super.key});
@override
State<ApiPage> createState() => _ApiPageState();
}
class _ApiPageState extends State<ApiPage> {
List<dynamic> posts = [];
bool loading = true;
@override
void initState() {
super.initState();
fetchPosts();
}
Future<void> fetchPosts() async {
final uri = Uri.parse('https://jsonplaceholder.typicode.com/posts?_limit=10');
final response = await http.get(uri);
if (response.statusCode == 200) {
setState(() {
posts = jsonDecode(response.body) as List<dynamic>;
loading = false;
});
} else {
setState(() => loading = false);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('API en Flutter')),
body: loading
? const Center(child: CircularProgressIndicator())
: ListView.builder(
itemCount: posts.length,
itemBuilder: (_, i) => ListTile(title: Text(posts[i]['title'])),
),
);
}
}Expected result
The screen loads remote items and displays them after a successful request.
Common mistakes
- Ignoring
statusCodechecks. - Decoding JSON without shape validation.
- Skipping loading and error UI states.
Practical use
This is the most common baseline for backend-powered mobile apps.
Recommended next exercise
- Firebase Auth Login in Flutter: solved email/password exercise
- SharedPreferences in Flutter: solved exercise for local settings
- FutureBuilder in Flutter: solved exercise for loading states
- All Flutter exercises
Guided practice and next step
- More Flutter exercises
- C exercises to strengthen fundamentals
- Programming in C in 100 Solved Exercises
- View the C book on Amazon (included in Kindle Unlimited)
- Subscribe to the newsletter
FAQ
Which package should I use for simple HTTP calls?
http is a reliable and lightweight option.
When should I use Dio instead?
When you need interceptors, retries, or advanced request configuration.
Do I need typed models from day one?
Not always, but typed models reduce bugs as complexity grows.