πΌNetworking
In Flutter, the http package is commonly used for sending HTTP requests to a server. Letβs explore how you can perform GET and POST requests.
1. Adding the http Package π¦
http Package π¦First, add the http package to your pubspec.yaml file:
dependencies:
flutter:
sdk: flutter
http: ^1.1.0Run flutter pub get to install the new dependency.
2. Sending a GET Request π€
Hereβs how you can send a GET request to fetch data from a server:
import 'package:http/http.dart' as http;
Future<void> fetchPost() async {
final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts/1'));
if (response.statusCode == 200) {
// If the server returns an OK response, parse the JSON
print('Response data: ${response.body}');
} else {
// If the server did not return a 200 OK response, throw an exception.
throw Exception('Failed to load post');
}
}3. Sending a POST Request π₯
Hereβs how you can send a POST request to create new data on a server:
4. Error Handling π
It's important to handle any errors that occur when sending requests:
Complete Example Code π
Let's put everything together in a complete Flutter app:

In this complete example:
We first add the
httpdependency inpubspec.yaml.We define a
NetworkingExamplestateful widget.In the
_NetworkingExampleStateclass, we define afetchDatamethod that sends a GET request to fetch data.We use a
FloatingActionButtonto trigger thefetchDatamethod.We display the fetched data or any error messages to the user.
Assignments π
Here are some exercises to reinforce your understanding:
Last updated
Was this helpful?