How to Use HTTP Package in Flutter for Network Requests
To use the
http package in Flutter, first add it to your pubspec.yaml file, then import it in your Dart code. Use http.get() or other HTTP methods to fetch data asynchronously and handle the response with await.Syntax
The http package provides functions like get, post, put, and delete to make HTTP requests. You use await to wait for the response asynchronously. The response contains status code and body data.
- import: Bring the package into your Dart file.
- http.get(Uri.parse(url)): Sends a GET request to the URL.
- await: Waits for the request to complete.
- response.statusCode: HTTP status code (e.g., 200 means success).
- response.body: The content returned by the server.
dart
import 'package:http/http.dart' as http; Future<void> fetchData() async { final url = Uri.parse('https://example.com/data'); final response = await http.get(url); if (response.statusCode == 200) { print('Data: ' + response.body); } else { print('Request failed with status: ' + response.statusCode.toString()); } }
Example
This example shows a simple Flutter app that fetches data from a URL when a button is pressed and displays the result on screen.
dart
import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; void main() => runApp(MyApp()); class MyApp extends StatefulWidget { @override State<MyApp> createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { String _data = 'Press the button to fetch data'; Future<void> _fetchData() async { final url = Uri.parse('https://jsonplaceholder.typicode.com/todos/1'); final response = await http.get(url); if (response.statusCode == 200) { setState(() { _data = response.body; }); } else { setState(() { _data = 'Failed to load data'; }); } } @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: Text('HTTP Package Example')), body: Center( child: Padding( padding: const EdgeInsets.all(16.0), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text(_data), SizedBox(height: 20), ElevatedButton( onPressed: _fetchData, child: Text('Fetch Data'), ), ], ), ), ), ), ); } }
Output
When the button is pressed, the app displays the JSON data fetched from the URL, for example: {"userId":1,"id":1,"title":"delectus aut autem","completed":false}
Common Pitfalls
Common mistakes when using the http package include:
- Not adding
awaitbefore the HTTP call, causing the app to not wait for the response. - Forgetting to parse the URL with
Uri.parse(), which is required. - Not checking
response.statusCodebefore usingresponse.body, leading to errors if the request failed. - Performing network calls on the main thread without
async/await, which can freeze the UI.
dart
/* Wrong way: Missing await and Uri.parse */ final response = http.get('https://example.com'); // Error: argument must be Uri /* Right way: */ final response = await http.get(Uri.parse('https://example.com'));
Quick Reference
Here is a quick summary of common http package methods and usage tips:
| Method | Description |
|---|---|
| http.get(Uri) | Send a GET request to the given URL |
| http.post(Uri, body) | Send a POST request with optional body data |
| http.put(Uri, body) | Send a PUT request to update data |
| http.delete(Uri) | Send a DELETE request to remove data |
| await | Use to wait for the HTTP request to complete |
| Uri.parse(String) | Convert a string URL to a Uri object |
Key Takeaways
Add the http package to pubspec.yaml and import it to use network requests.
Always use Uri.parse() to convert string URLs before making requests.
Use async/await to handle HTTP calls without freezing the UI.
Check response.statusCode before using response.body to handle errors.
Use setState to update UI after receiving data in Flutter apps.