Flutter HTTP Tutorial – A Complete Guide

flutter-http-example
flutter-http-example

In this tutorial, we’re going to learn about how to make HTTP requests with flutter. To start with that, we need to create a flutter project

flutter create httpdemo
<span class="hljs-built_in">cd</span> httpdemo

What you’ll learn

  • Read (GET) Data from the webserver
  • POST data to a web server

This example, we’re going to use http://reqres.in/ as our server

To working with HTTP, we need to include the following package with our pubspec.yaml file

<span class="hljs-symbol">dependencies:</span>
<span class="hljs-symbol">  flutter:</span>
<span class="hljs-symbol">    sdk:</span> flutter
<span class="hljs-symbol">  http:</span> ^<span class="hljs-number">0.12</span><span class="hljs-number">.0</span>+<span class="hljs-number">2</span>
<span class="hljs-symbol">  toast:</span> ^<span class="hljs-number">0.1</span><span class="hljs-number">.5</span>

HTTP helps you to make requests & toast allows you to display toast message.

Reading JSON with Flutter

First, we’re going to read user’s data from http://reqres.in/api/users. Response look like this

    {
<span class="hljs-symbol">    page:</span> <span class="hljs-number">1</span>,
<span class="hljs-symbol">    per_page:</span> <span class="hljs-number">3</span>,
<span class="hljs-symbol">    total:</span> <span class="hljs-number">12</span>,
<span class="hljs-symbol">    total_pages:</span> <span class="hljs-number">4</span>,
<span class="hljs-symbol">    data:</span> [
        {
<span class="hljs-symbol">            id:</span> <span class="hljs-number">1</span>,
<span class="hljs-symbol">            email:</span> <span class="hljs-string">"[email protected]"</span>,
<span class="hljs-symbol">            first_name:</span> <span class="hljs-string">"George"</span>,
<span class="hljs-symbol">            last_name:</span> <span class="hljs-string">"Bluth"</span>,
<span class="hljs-symbol">            avatar:</span> <span class="hljs-string">"http://s3.amazonaws.com/uifaces/faces/twitter/calebogden/128.jpg"</span>
        },
        {
<span class="hljs-symbol">            id:</span> <span class="hljs-number">2</span>,
<span class="hljs-symbol">            email:</span> <span class="hljs-string">"[email protected]"</span>,
<span class="hljs-symbol">            first_name:</span> <span class="hljs-string">"Janet"</span>,
<span class="hljs-symbol">            last_name:</span> <span class="hljs-string">"Weaver"</span>,
<span class="hljs-symbol">            avatar:</span> <span class="hljs-string">"http://s3.amazonaws.com/uifaces/faces/twitter/josephstein/128.jpg"</span>
        },
        {
<span class="hljs-symbol">            id:</span> <span class="hljs-number">3</span>,
<span class="hljs-symbol">            email:</span> <span class="hljs-string">"[email protected]"</span>,
<span class="hljs-symbol">            first_name:</span> <span class="hljs-string">"Emma"</span>,
<span class="hljs-symbol">            last_name:</span> <span class="hljs-string">"Wong"</span>,
<span class="hljs-symbol">            avatar:</span> <span class="hljs-string">"http://s3.amazonaws.com/uifaces/faces/twitter/olegpogodaev/128.jpg"</span>
        }
    ]
}

Let’s import the required packages first

<span class="hljs-keyword">import</span> <span class="hljs-string">'package:http/http.dart'</span> <span class="hljs-keyword">as</span> http;
<span class="hljs-keyword">import</span> <span class="hljs-string">'dart:convert'</span>;

Since we’re working with JSON data, we need to import dart:convert. Now we need to create a function which make a GET request with our URL

List _users = []<span class="hljs-comment">;</span>

getUsers() async {
    http.get(<span class="hljs-string">"http://reqres.in/api/users"</span>).then((res) {
        Map userData = json.decode(res.body)<span class="hljs-comment">;</span>
        setState(() {
        _users = userData[<span class="hljs-string">"data"</span>]<span class="hljs-comment">;</span>
        })<span class="hljs-comment">;</span>
    })<span class="hljs-comment">;</span>
}

Explanation:

  • We created _users to store the response from server
  • http.get(url) received data & we have used json.decode for converting response as JSON
  • once data is received, we’re updating _users

Displaying data

<span class="hljs-variable">@override</span>
Widget build(BuildContext context) {
    <span class="hljs-selector-tag">return</span> <span class="hljs-selector-tag">Scaffold</span>(
        <span class="hljs-attribute">appBar</span>: AppBar(
        <span class="hljs-attribute">title</span>: Text(<span class="hljs-string">"Users"</span>),
        <span class="hljs-attribute">actions</span>: <Widget>[
            IconButton(
            <span class="hljs-attribute">icon</span>: Icon(Icons.refresh),
            <span class="hljs-attribute">onPressed</span>: () => getUsers(),
            )
        ],
        ),
        <span class="hljs-attribute">body</span>: _users.length == <span class="hljs-number">0</span>
            ? Center(<span class="hljs-attribute">child</span>: Text(<span class="hljs-string">"No user Found"</span>))
            : ListView.builder(
                <span class="hljs-attribute">itemCount</span>: _users.length,
                <span class="hljs-attribute">itemBuilder</span>: (context, index) {
                return ListTile(
                    <span class="hljs-attribute">leading</span>: CircleAvatar(
                        <span class="hljs-attribute">backgroundImage</span>: NetworkImage(_users[index][<span class="hljs-string">'avatar'</span>])),
                    <span class="hljs-attribute">title</span>: Text(_users[index][<span class="hljs-string">'first_name'</span>] +
                        <span class="hljs-string">" "</span> +
                        _users[index][<span class="hljs-string">'last_name'</span>]),
                );
                },
            ),
    );
}

Explanation:

  • We’re checking _users.length == 0, if yes, we display no user found, otherwise, we display data with listview


Making HTTP POST

Now, we’re going to make an HTTP post request to http://reqres.in/api/register. for that we need

{
    <span class="hljs-attr">"email"</span>: <span class="hljs-string">"[email protected]"</span>,
    <span class="hljs-attr">"password"</span>: <span class="hljs-string">"pistol"</span>
}

Let’s create a simple form for receiving inputs from the user such as email and password


Map<String,String> _user = {};

<span class="hljs-meta">@override</span>
    Widget build(BuildContext context) {
    <span class="hljs-comment">// <span class="hljs-doctag">TODO:</span> implement build</span>
    <span class="hljs-keyword">return</span> Scaffold(
<span class="hljs-symbol">        appBar:</span> AppBar(
<span class="hljs-symbol">        title:</span> Text(<span class="hljs-string">"Register"</span>),
        ),
<span class="hljs-symbol">        body:</span> Container(
<span class="hljs-symbol">        padding:</span> EdgeInsets.all(<span class="hljs-number">32.0</span>),
<span class="hljs-symbol">        child:</span> Column(
<span class="hljs-symbol">            crossAxisAlignment:</span> CrossAxisAlignment.start,
<span class="hljs-symbol">            children:</span> <Widget>[
            TextField(<span class="hljs-string">decoration:</span> InputDecoration(<span class="hljs-string">hintText:</span> <span class="hljs-string">"Email"</span>), <span class="hljs-string">onChanged:</span>(val){
                setState(() {
                _user[<span class="hljs-string">'email'</span>] = val;
                });
            }),

            TextField(<span class="hljs-string">obscureText:</span> <span class="hljs-literal">true</span> , <span class="hljs-string">decoration:</span> InputDecoration(<span class="hljs-string">hintText:</span> <span class="hljs-string">"Password"</span>), <span class="hljs-string">onChanged:</span>(val){
                setState(() {
                _user[<span class="hljs-string">'password'</span>] = val;
                });
            }),
            OutlineButton(
<span class="hljs-symbol">                child:</span> Text(<span class="hljs-string">"Register"</span>),
<span class="hljs-symbol">                onPressed:</span> () {
                register();
                },
            )
            ],
        ),
        ),
    );
}

Explanation:

  • We created _user variable for storing user info
  • We created TextField for getting email and password
  • When user press register button we’re calling register()
register(){
    http.post(<span class="hljs-string">"http://reqres.in/api/register"</span>,
        body: _user 
    ).<span class="hljs-keyword">then</span>((res){
        <span class="hljs-built_in">var</span> resJson = json.decode(res.body);

        <span class="hljs-keyword">if</span>(resJson['<span class="hljs-built_in">error</span>'] != null){
        Toast.<span class="hljs-built_in">show</span>(<span class="hljs-string">"Something Went wrong -> "</span> + resJson['<span class="hljs-built_in">error</span>'], <span class="hljs-built_in">context</span>, gravity: Toast.CENTER);
        }
        <span class="hljs-keyword">else</span>{
        Toast.<span class="hljs-built_in">show</span>(<span class="hljs-string">"Registerd Successfully"</span>, <span class="hljs-built_in">context</span>, gravity: Toast.CENTER);
        }
    });
}

Explanation:

  • we’re making requests using http.post() with URL & converted response to JSON. Based on the response we’re displaying toast message