0
0
Fluttermobile~20 mins

http package in Flutter - Mini App: Build & Ship

Choose your learning style9 modes available
Build: Simple HTTP Fetch Screen
This screen fetches a message from a web server and displays it.
Target UI
-------------------------
| Simple HTTP Fetch     |
|-----------------------|
|                       |
| [Fetch Message]       |
|                       |
| Message:              |
|                       |
|                       |
-------------------------
Add a button labeled 'Fetch Message'.
When tapped, it sends a GET request to https://jsonplaceholder.typicode.com/posts/1.
Display the 'title' field from the JSON response below the button.
Show a loading indicator while fetching.
Show an error message if the request fails.
Starter Code
Flutter
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

class SimpleHttpFetchScreen extends StatefulWidget {
  @override
  State<SimpleHttpFetchScreen> createState() => _SimpleHttpFetchScreenState();
}

class _SimpleHttpFetchScreenState extends State<SimpleHttpFetchScreen> {
  String _message = '';
  bool _loading = false;
  String _error = '';

  // TODO: Add fetchMessage function here

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Simple HTTP Fetch')),
      body: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          children: [
            ElevatedButton(
              onPressed: () {
                // TODO: Call fetchMessage here
              },
              child: const Text('Fetch Message'),
            ),
            const SizedBox(height: 20),
            if (_loading) const CircularProgressIndicator(),
            if (_error.isNotEmpty) Text(_error, style: const TextStyle(color: Colors.red)),
            if (_message.isNotEmpty) Text('Message: $_message'),
          ],
        ),
      ),
    );
  }
}
Task 1
Task 2
Solution
Flutter
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

class SimpleHttpFetchScreen extends StatefulWidget {
  @override
  State<SimpleHttpFetchScreen> createState() => _SimpleHttpFetchScreenState();
}

class _SimpleHttpFetchScreenState extends State<SimpleHttpFetchScreen> {
  String _message = '';
  bool _loading = false;
  String _error = '';

  Future<void> fetchMessage() async {
    setState(() {
      _loading = true;
      _error = '';
      _message = '';
    });
    try {
      final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts/1'));
      if (response.statusCode == 200) {
        final data = json.decode(response.body);
        setState(() {
          _message = data['title'] ?? 'No title found';
        });
      } else {
        setState(() {
          _error = 'Error: Server returned status ${response.statusCode}';
        });
      }
    } catch (e) {
      setState(() {
        _error = 'Error: Could not fetch data';
      });
    } finally {
      setState(() {
        _loading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Simple HTTP Fetch')),
      body: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          children: [
            ElevatedButton(
              onPressed: fetchMessage,
              child: const Text('Fetch Message'),
            ),
            const SizedBox(height: 20),
            if (_loading) const CircularProgressIndicator(),
            if (_error.isNotEmpty) Text(_error, style: const TextStyle(color: Colors.red)),
            if (_message.isNotEmpty) Text('Message: $_message'),
          ],
        ),
      ),
    );
  }
}

This solution uses the http package to send a GET request to a sample API.

The fetchMessage function is asynchronous and updates the UI state before, during, and after the request.

It shows a loading spinner while waiting, displays the fetched title on success, and shows an error message if something goes wrong.

The button triggers this function when pressed.

Final Result
Completed Screen
-------------------------
| Simple HTTP Fetch     |
|-----------------------|
|                       |
| [Fetch Message]       |
|                       |
| Message: sunt aut ...  |
|                       |
|                       |
-------------------------
User taps 'Fetch Message' button.
A spinner appears while loading.
After loading, the message title from the API appears below the button.
If an error occurs, a red error message is shown instead.
Stretch Goal
Add a retry button that appears only when an error occurs to try fetching the message again.
💡 Hint
Show a new ElevatedButton with label 'Retry' below the error message that calls fetchMessage when tapped.