Flutter API Call with http: solved REST exercise

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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
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 statusCode checks.
  • Decoding JSON without shape validation.
  • Skipping loading and error UI states.

Practical use

This is the most common baseline for backend-powered mobile apps.

Guided practice and next step

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.