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 π¦
First, add the http package to your pubspec.yaml file:
dependencies:flutter:sdk:flutterhttp:^1.1.0
Run 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 JSONprint('Response data: ${response.body}'); } else {// If the server did not return a 200 OK response, throw an exception.throwException('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:
import'package:http/http.dart'as http;Future<void> createPost() async {final response =await http.post(Uri.parse('https://jsonplaceholder.typicode.com/posts'), body: {'title':'foo','body':'bar','userId':'1', }, );if (response.statusCode ==201) {// If the server returns a CREATED response, parse the JSONprint('Created post: ${response.body}'); } else {// If the server did not return a 201 CREATED response, throw an exception.throwException('Failed to create post'); }}
4. Error Handling π
It's important to handle any errors that occur when sending requests:
try {awaitfetchPost();} catch (error) {print('Failed to load post: $error');}
Complete Example Code π
Let's put everything together in a complete Flutter app: