How to send post requests to an API in Flutter App
2 min readFeb 3, 2023
Here’s a step-by-step guide to creating a Flutter app that sends a POST request to an API:
- Create a new Flutter project in your preferred IDE.
- Choose an API to connect to, or create your own REST API.
- Add the required dependencies
http
in thepubspec.yaml
file, for making HTTP requests. - In the
main.dart
file, create a UI with a form to collect the data you want to send in the POST request. - Create a function to send the POST request using the
http
package or another library of your choice. - Call the function to send the POST request in response to a user action, such as clicking a button.
- Verify that the request was sent successfully by checking the response from the API.
Here is an example of how you could send a POST request in Flutter using the http
package:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter POST Request Example',
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
final apiUrl = "https://jsonplaceholder.typicode.com/posts";
TextEditingController titleController = TextEditingController();
TextEditingController bodyController = TextEditingController();
Future<void> sendPostRequest() async {
var response = await http.post(apiUrl,
headers: {"Content-Type": "application/json"},
body: jsonEncode({
"title": titleController.text,
"body": bodyController.text,
"userId": 1,
}));
if (response.statusCode == 201) {
Scaffold.of(context).showSnackBar(SnackBar(
content: Text("Post created successfully!"),
));
} else {
Scaffold.of(context).showSnackBar(SnackBar(
content: Text("Failed to create post!"),
));
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter POST Request Example'),
),
body: Padding(
padding: EdgeInsets.all(16.0),
child: Column(
children: <Widget>[
TextField(
controller: titleController,
decoration: InputDecoration(hintText: "Title"),
),
TextField(
controller: bodyController,
decoration: InputDecoration(hintText: "Body"),
),
RaisedButton(
onPressed: sendPostRequest,
child: Text("Create Post"),
),
],
),
),
);
This example demonstrates how to send data to a REST API using Flutter. You can modify this code to implement the other CRUD operations per your requirements.