------------------------- | Simple HTTP Fetch | |-----------------------| | | | [Fetch Message] | | | | Message: | | | | | -------------------------
http package in Flutter - Mini App: Build & Ship
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'), ], ), ), ); } }
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.
------------------------- | Simple HTTP Fetch | |-----------------------| | | | [Fetch Message] | | | | Message: sunt aut ... | | | | | -------------------------
Practice
What does the http.get() function do in Flutter's http package?
Solution
Step 1: Understand the purpose of
Thehttp.get()http.get()method is used to request data from a specified URL.Step 2: Differentiate from other HTTP methods
Sending data useshttp.post(), deleting useshttp.delete(), and updating useshttp.put()orhttp.patch().Final Answer:
It fetches data from a given URL. -> Option CQuick Check:
http.get() = fetch data [OK]
- Confusing get() with post()
- Thinking get() sends data
- Mixing HTTP methods
Which of the following is the correct way to create a URI for http.get() in Flutter?
http.get(???);Solution
Step 1: Check the required argument type for
Thehttp.get()http.get()method requires aUriobject, not a plain string.Step 2: Use
The correct way is to wrap the URL string withUri.parse()to convert string to UriUri.parse()to create a Uri object.Final Answer:
http.get(Uri.parse('https://example.com')) -> Option AQuick Check:
Use Uri.parse() for URLs in http.get() [OK]
- Passing URL as plain string
- Using Uri() constructor incorrectly
- Trying Uri.https() without parameters
What will be printed by this Flutter code snippet?
import 'package:http/http.dart' as http;
void fetchData() async {
final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts/1'));
if (response.statusCode == 200) {
print('Success');
} else {
print('Failed');
}
}
fetchData();Solution
Step 1: Analyze the HTTP GET request
The code requests a valid URL that returns a post with status code 200 on success.Step 2: Check the status code condition
If the status code is 200, it prints 'Success'; otherwise, 'Failed'. The URL is valid and should return 200.Final Answer:
Success -> Option BQuick Check:
Status code 200 means Success [OK]
- Assuming any response prints 'Failed'
- Ignoring async/await usage
- Not checking statusCode properly
Identify the error in this Flutter code using the http package:
import 'package:http/http.dart' as http;
void sendData() async {
final response = await http.post('https://example.com/api/data');
if (response.statusCode == 201) {
print('Created');
}
}Solution
Step 1: Check the argument type for
Thehttp.post()http.post()method requires aUriobject, not a plain string.Step 2: Identify missing
The URL string should be wrapped withUri.parse()Uri.parse()to convert it to a Uri object.Final Answer:
Missing Uri.parse() around the URL string. -> Option DQuick Check:
http.post() needs Uri.parse() for URL [OK]
- Passing URL as string directly
- Confusing status codes 200 and 201
- Forgetting async/await with http calls
You want to send JSON data using http.post() in Flutter. Which code snippet correctly sends a JSON body and sets the content type header?
import 'package:http/http.dart' as http;
import 'dart:convert';
void sendJson() async {
final url = Uri.parse('https://example.com/api');
final response = await http.post(
url,
headers: ???,
body: ???,
);
}Solution
Step 1: Set the correct header for JSON
The header must be{'Content-Type': 'application/json'}to tell the server the body is JSON.Step 2: Encode the body as JSON string
The body must be a string, so usejsonEncode()to convert the map to a JSON string.Final Answer:
{'Content-Type': 'application/json'}, jsonEncode({'key': 'value'}) -> Option AQuick Check:
Headers + jsonEncode() = correct JSON POST [OK]
- Passing map directly as body
- Wrong content-type header
- Using json.decode() instead of jsonEncode()
Ready to prove it?
Pass the test and this pattern moves unknown
