Flutter HTTP POST :
Flutter HTTP POST request method is used to fetch the values from the api based on user provided input which means when you are trying to find out the result of a exam you will provide a hall ticket number as input parameter.
In the same way when you are trying to search for a employee details in database you need to provide the employee id so that you can get the details of that particular employee out of all the employees data.
The best example for the post request is the dictionary app, search engines like youtube, google, facebook and more where you search for the data and based on which you get back the result.
In this part of the tutorial we will be dealing with the flutter HTTP POST request method with a simple example for you better understanding in the previous tutorials we have seen the request made through retrofit library can check them here.
Project Structure :
This image shows the project structure of the flutter HTTP POST request method.
pubspec.yaml :
Add the dependencies http and update the version accordingly to avoid issues.
dependencies: flutter: sdk: flutter http: ^0.12.1
Posts.dart :
Create a model class where we can specify the variables which we use to parse the data like id, title and body from the api.
final int id; final String title; final String body;
Create the constructor to make use of these variables
Posts({this.id, this.title, this.body});
Parse the variables based on their key values.
factory Posts.fromJson(Map<String, dynamic> json) { return Posts( id: json['id'], title: json['title'], body: json['body'], ); }
class Posts { final int id; final String title; final String body; Posts({this.id, this.title, this.body}); factory Posts.fromJson(Map<String, dynamic> json) { return Posts( id: json['id'], title: json['title'], body: json['body'], ); } }
Network.dart :
We need to declare the api used to fetch data
https://jsonplaceholder.typicode.com/posts/${num}
Here we are posting the num for which related data will be return back in form of response.
We need to declare a async method so that we can wait for the response to be back
Future<Posts> fetchPosts(String num) async { }
If response is success we will post back the data to be parsed based on the key values
if (response.statusCode == 200) { // If the server did return a 200 OK response, // then parse the JSON. return Posts.fromJson(json.decode(response.body)); }
If the response is failure then we will throw a sample message stating the exception.
else { // If the server did not return a 200 OK response, // then throw an exception. throw Exception('Failed to load album'); }
import 'dart:convert'; import 'package:http/http.dart' as http; import 'Posts.dart'; Future<Posts> fetchPosts(String num) async { final response = await http.get('https://jsonplaceholder.typicode.com/posts/${num}'); if (response.statusCode == 200) { // If the server did return a 200 OK response, // then parse the JSON. return Posts.fromJson(json.decode(response.body)); } else { // If the server did not return a 200 OK response, // then throw an exception. throw Exception('Failed to load album'); } }
main.dart :
Initialize the app with void main()
void main() => runApp(MyApp());
Create a default class MyApp and a state
class MyApp extends StatefulWidget { MyApp({Key key}) : super(key: key); @override _MyAppState createState() => _MyAppState(); }
Declare variables text editing controller and boolean
TextEditingController postNum = TextEditingController();
bool pressed = false;
Inside the MaterialApp declare a scaffold in home widget
MaterialApp( title: 'Fetch Photos', theme: ThemeData( primarySwatch: Colors.blue, ), home: );
Inside the scaffold declare a appBar
appBar: AppBar( title: Text('Fetch Data With Http Call'), ),
In the body widget declare a Column where we provide a textfield to take user input and and raised button to post the input to the api and listen for output.
Column( children: <Widget>[ TextField( controller: postNum, decoration: InputDecoration( hintText: "Enter Post Id", border: InputBorder.none, ), ), RaisedButton(child: Text("Fetch Post"), onPressed: () => {setState(() { pressed = true; //fetchData(postNum); })}), pressed ? fetchData(postNum): SizedBox(), ], ),
Declare a FutureBuilder to accept user input and post it to api and listen for the output.
FutureBuilder<Posts> fetchData(postNum) { return FutureBuilder<Posts>( future: fetchPosts(postNum.text.toString()), builder: (context, snapshot) { if (snapshot.hasData) { return getData(snapshot); } else if (snapshot.hasError) { return Text("${snapshot.error}"); } // By default, show a loading spinner. return CircularProgressIndicator(); }, ); }
After fetching the data parse the data on to the screen using this method.
Widget getData(snapshot) { return Padding( padding: const EdgeInsets.all(35.0), child: Column( children: <Widget>[ Padding(padding: EdgeInsets.all(20)), Text("Title : " + snapshot.data.title, style: TextStyle(fontSize: 20)), Padding(padding: EdgeInsets.all(20)), Text("Body : " + snapshot.data.body, style: TextStyle(fontSize: 20)), ], ), ); }
Flutter http post FullCode :
We are providing the code for flutter http post
import 'package:flutter/material.dart'; import 'Posts.dart'; import 'Network.dart'; void main() => runApp(MyApp()); class MyApp extends StatefulWidget { MyApp({Key key}) : super(key: key); @override _MyAppState createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { TextEditingController postNum = TextEditingController(); bool pressed = false; @override Widget build(BuildContext context) { return MaterialApp( title: 'Fetch Photos', theme: ThemeData( primarySwatch: Colors.blue, ), home: Scaffold( appBar: AppBar( title: Text('Fetch Data With Http Call'), ), body: Column( children: <Widget>[ TextField( controller: postNum, decoration: InputDecoration( hintText: "Enter Post Id", border: InputBorder.none, ), ), RaisedButton(child: Text("Fetch Post"), onPressed: () => {setState(() { pressed = true; //fetchData(postNum); })}), pressed ? fetchData(postNum): SizedBox(), ], ), ), ); } } FutureBuilder<Posts> fetchData(postNum) { return FutureBuilder<Posts>( future: fetchPosts(postNum.text.toString()), builder: (context, snapshot) { if (snapshot.hasData) { return getData(snapshot); } else if (snapshot.hasError) { return Text("${snapshot.error}"); } // By default, show a loading spinner. return CircularProgressIndicator(); }, ); } Widget getData(snapshot) { return Padding( padding: const EdgeInsets.all(35.0), child: Column( children: <Widget>[ Padding(padding: EdgeInsets.all(20)), Text("Title : " + snapshot.data.title, style: TextStyle(fontSize: 20)), Padding(padding: EdgeInsets.all(20)), Text("Body : " + snapshot.data.body, style: TextStyle(fontSize: 20)), ], ), ); }
Flutter http post Output :
This screen depicts the usage of the flutter HTTP Post request method