HTTP CRUD methods in Flutter
HTTP CRUD methods are used to interact with RESTful APIs, which are a popular way to build web services. Flutter provides a number of packages that make it easy to send HTTP requests and handle responses, including the http package.
In this blog post, I will cover the basics of HTTP CRUD methods in Flutter using the http package. Specifically, I will cover how to:
- Send HTTP GET requests to retrieve data
- Send HTTP POST requests to create new data
- Send HTTP PUT requests to update existing data
- Send HTTP DELETE requests to delete data
We will also provide sample code snippets for each method so you can follow along.
Step 1: Import the http package
To use the http package, you will need to add it to your pubspec.yaml file and import it in your Dart code. Here’s how you can do that:
import 'package:http/http.dart' as http;
Step 2: Send HTTP GET requests
HTTP GET requests are used to retrieve data from a server. Here’s how you can send an HTTP GET request using the http package:
Future<List<dynamic>> fetchData() async {
final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts'));
if (response.statusCode == 200) {
return jsonDecode(response.body);
} else {
throw Exception('Failed to load data');
}
}
This code sends an HTTP GET request to the URL https://jsonplaceholder.typicode.com/posts, which is a fake RESTful API for testing purposes. If the response status code is 200, which indicates success, the response body is decoded from JSON and returned as a list of dynamic objects. Otherwise, an exception is thrown.
Step 3: Send HTTP POST requests
HTTP POST requests are used to create new data on a server. Here’s how you can send an HTTP POST request using the http package:
Future<void> createData() async {
final response = await http.post(Uri.parse('https://jsonplaceholder.typicode.com/posts'),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode(<String, dynamic>{
'title': 'Flutter HTTP CRUD',
'body': 'This is a blog post about HTTP CRUD methods in Flutter',
'userId': 1,
}));
if (response.statusCode != 201) {
throw Exception('Failed to create data');
}
}
This code sends an HTTP POST request to the same URL as before, but with a different payload in the body. The body is a JSON-encoded map with three fields: title, body, and userId. If the response status code is not 201, which indicates success, an exception is thrown.
Step 4: Send HTTP PUT requests
HTTP PUT requests are used to update existing data on a server. Here’s how you can send an HTTP PUT request using the http package:
Future<void> updateData(int id) async {
final response = await http.put(Uri.parse('https://jsonplaceholder.typicode.com/posts/$id'),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode(<String, dynamic>{
'title': 'Flutter HTTP CRUD',
'body': 'This is an updated blog post about HTTP CRUD methods in Flutter',
'userId': 1,
}));
if (response.statusCode != 200) {
throw Exception('Failed to update data');
}
}
This code sends an HTTP PUT request to update an existing post on the server. The URL includes the ID of the post to be updated, and the body is a JSON-encoded map with the same fields as in the HTTP POST example. If the response status code is not 200, an exception is thrown.
Step 5: Send HTTP DELETE requests
HTTP DELETE requests are used to delete data on a server. Here’s how you can send an HTTP DELETE request using the http package:
Future<void> deleteData(int id) async {
final response = await http.delete(Uri.parse('https://jsonplaceholder.typicode.com/posts/$id'));
if (response.statusCode != 200) {
throw Exception('Failed to delete data');
}
}
This code sends an HTTP DELETE request to delete a post on the server. The URL includes the ID of the post to be deleted. If the response status code is not 200, an exception is thrown.
Step 6: Putting it all together
Now that we’ve covered the basics of HTTP CRUD methods in Flutter using the http package, let’s put it all together in a sample app. Here’s an example app that retrieves a list of posts from the server, displays them in a ListView, and allows the user to create, update, and delete posts.
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 HTTP CRUD',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter HTTP CRUD'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
List<dynamic> _data = [];
@override
void initState() {
super.initState();
_fetchData();
}
Future<void> _fetchData() async {
try {
final response = await http
.get(Uri.parse('https://jsonplaceholder.typicode.com/posts'));
if (response.statusCode == 200) {
setState(() {
_data = jsonDecode(response.body);
});
} else {
throw Exception('Failed to load data');
}
} catch (error) {
print(error);
}
}
Future<void> _createData() async {
try {
final response = await http.post(
Uri.parse('https://jsonplaceholder.typicode.com/posts'),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode(<String, dynamic>{
'title': 'Flutter HTTP CRUD',
'body': 'This is a blog post about HTTP CRUD methods in Flutter',
'userId': 1,
}));
if (response.statusCode == 201) {
_fetchData();
} else {
throw Exception('Failed to create data');
}
} catch (error) {
print(error);
}
}
Future<void> _updateData(int id) async {
try {
final response = await http.put(
Uri.parse('https://jsonplaceholder.typicode.com/posts/$id'),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode(<String, dynamic>{
'title': 'Flutter HTTP CRUD',
'body':
'This is an updated blog post about HTTP CRUD methods in Flutter',
}));
if (response.statusCode == 200) {
_fetchData();
} else {
throw Exception('Failed to update data');
}
} catch (error) {
print(error);
}
}
Future<void> _deleteData(int id) async {
try {
final response = await http
.delete(Uri.parse('https://jsonplaceholder.typicode.com/posts/$id'));
if (response.statusCode == 200) {
_fetchData();
} else {
throw Exception('Failed to delete data');
}
} catch (error) {
print(error);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: ListView.builder(
itemCount: _data.length,
itemBuilder: (BuildContext context, int index) {
final data = _data[index];
return ListTile(
title: Text(data['title']),
subtitle: Text(data['body']),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
IconButton(
icon: Icon(Icons.edit),
onPressed: () => _updateData(data['id']),
),
IconButton(
icon: Icon(Icons.delete),
onPressed: () => _deleteData(data['id']),
),
],
),
);
},
),
floatingActionButton: FloatingActionButton(
onPressed: _createData,
tooltip: 'Create',
child: Icon(Icons.add),
),
);
}
}
This app uses the http package to send HTTP requests to a JSONPlaceholder API. It retrieves a list of posts from the server, displays them in a ListView, and allows the user to create, update, and delete posts.
Conclusion
In this blog post, we’ve covered the basics of HTTP CRUD methods in Flutter using the http package. We’ve discussed how to send HTTP GET, POST, PUT, and DELETE requests, and we’ve put it all together in a sample app.
HTTP CRUD methods are essential for any app that communicates with a server, and Flutter makes it easy to send these requests using the http package. By mastering these methods, you can build robust and dynamic apps that can create, read, update, and delete data from a server.
I hope you found this blog post helpful, and feel free to experiment with the sample app and try new HTTP requests. Good luck with your Flutter development!