Flutter API Call with http: solved REST exercise

  2 minutes

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.

Build a screen with:

  • fetch data from a public REST endpoint
  • decode JSON payload
  • render list results safely
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'])),
            ),
    );
  }
}

The screen loads remote items and displays them after a successful request.

  • Ignoring statusCode checks.
  • Decoding JSON without shape validation.
  • Skipping loading and error UI states.

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

http is a reliable and lightweight option.

When you need interceptors, retries, or advanced request configuration.

Not always, but typed models reduce bugs as complexity grows.