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.