POST, DELETE and PUT Requests
Preparation
Before starting we’ll need to add http as a dependency, so let’s edit our pubspec.yaml
file and add http:
dependencies:
http: <latest_version>
Then we’ll just need to do a good old flutter pub get
and import it in our file. I will use as a test case an ideal API Wrapper in order to call a single function to do all the work for us:
POST, DELETE and PUT
Those three methods work similarly to GET but we expect to add some body parameters. Fear not gentle developer!
With the call we can add a String body with a jsonEncoded Map<String,String>
which will be body parameters: then we only need to use http package with post
, delete
or put
method:
Ex
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
Future<void> createAlbum() async {
final headers = {
'Content-Type': 'application/json; charset=UTF-8',
};
Map<String, dynamic> body = {
'title': "praveen",
};
final http.Response response = await http.post(
Uri.parse('https://jsonplaceholder.typicode.com/albums'),
headers:headers,
body: jsonEncode(body),
);
if (response.statusCode == 201) {
print(response.body);
} else {
throw Exception('Failed to create album.');
}
}
@override
void initState() {
// TODO: implement initState
createAlbum();
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
createAlbum();
},
tooltip: 'Increment',
child: const Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
Output
Comments
Post a Comment