How to Make HTTP Request in Flutter: Simple Guide
In Flutter, you make HTTP requests using the
http package by calling methods like http.get() or http.post(). You import the package, then use async functions with await to fetch or send data over the internet.Syntax
To make an HTTP request in Flutter, first import the http package. Use async functions and await to wait for the response. Common methods include http.get() for fetching data and http.post() for sending data.
- http.get(Uri url): Sends a GET request to the given URL.
- http.post(Uri url, {body}): Sends a POST request with optional body data.
- Response: The object returned containing status code and body.
dart
import 'package:http/http.dart' as http; Future<void> fetchData() async { final response = await http.get(Uri.parse('https://example.com')); if (response.statusCode == 200) { print('Success: ' + response.body); } else { print('Error: ' + response.statusCode.toString()); } }
Example
This example shows how to fetch JSON data from a public API and print the response body. It demonstrates using http.get(), checking the status code, and handling the response asynchronously.
dart
import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { Future<String> fetchPost() async { final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts/1')); if (response.statusCode == 200) { return response.body; } else { throw Exception('Failed to load post'); } } @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: Text('HTTP Request Example')), body: Center( child: FutureBuilder<String>( future: fetchPost(), builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.waiting) { return CircularProgressIndicator(); } else if (snapshot.hasError) { return Text('Error: ${snapshot.error}'); } else { return SingleChildScrollView( padding: EdgeInsets.all(16), child: Text(snapshot.data ?? ''), ); } }, ), ), ), ); } }
Output
{"userId":1,"id":1,"title":"sunt aut facere repellat provident occaecati excepturi optio reprehenderit","body":"quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"}
Common Pitfalls
Common mistakes when making HTTP requests in Flutter include:
- Not adding
awaitbefore the request, causing the code to run before the response arrives. - Forgetting to parse the URL with
Uri.parse(). - Not checking the
statusCodebefore using the response body. - Ignoring exceptions that can crash the app.
Always handle errors and use async/await properly.
dart
import 'package:http/http.dart' as http; // Wrong way: missing await and Uri.parse void wrongRequest() { final response = http.get(Uri.parse('https://example.com')); print(response.body); // This will cause error } // Right way: Future<void> rightRequest() async { final response = await http.get(Uri.parse('https://example.com')); if (response.statusCode == 200) { print(response.body); } else { print('Request failed with status: ${response.statusCode}'); } }
Quick Reference
Here is a quick summary of key points for HTTP requests in Flutter:
| Concept | Description |
|---|---|
| Import package | import 'package:http/http.dart' as http; |
| GET request | await http.get(Uri.parse('https://url.com')); |
| POST request | await http.post(Uri.parse('https://url.com'), body: {...}); |
| Check status | if (response.statusCode == 200) {...} |
| Handle errors | Use try-catch or check status code |
Key Takeaways
Use the http package and async/await to make HTTP requests in Flutter.
Always parse URLs with Uri.parse() before sending requests.
Check the response status code before using the response data.
Handle exceptions to avoid app crashes during network calls.
Use FutureBuilder to display data fetched asynchronously in the UI.