We noticed you're using an ad blocker

Our website is made possible by displaying online advertisements to our visitors. Please consider supporting us by disabling your ad blocker.

Flutter REST API tutorial

club-football-league

FootballDesk

Get update standing EPL, UEFA, LaLiga and more

Get Now

Working with REST API is a common task on the current mobile application workflow. In flutter, it's an easy task to work with REST API. If you are finding a step by step tutorial on Flutter REST API call with an example then you are in right place. In this post, I'll show you a step by step tutorial on how to make HTTP request on REST API and feed JSON data to our application.

 

Work with REST API in Flutter

  1. Add HTTP package.
  2. Add permission.
  3. Make HTTP call to JSON API service.
  4. Make a Listview with API data.

 

Add HTTP package

First, add the Flutter HTTP package into your pubspec.yaml file in the dependency section.

dependencies:
  http: <latest_version>

 

Add permission

Add the internet permission into AndroidManifest.xml file.

<uses-permission android:name="android.permission.INTERNET" />

 

Make HTTP call to JSON API service

In this section, We sent an HTTP GET request to our JSON API service. Here I'm using a demo JSON API service which will return me a list of demo user data. To make an HTTP request, make a future type method.

Use these lines of import statements.

import 'dart:async' show Future;
import 'dart:convert';
import 'package:http/http.dart' as http;

Future method for getting data from JSON API.

List users;
bool loading = false;

Future<String> getUsers() async {
    setState(() => this.loading = true);
    var response = await http.get('https://jsonplaceholder.typicode.com/users');
    setState(() => users = json.decode(response.body.toString()));
    setState(() => this.loading = false);
    return 'success';
}

I have declared a users list and a bool type variable loading for showing loading an indication when our app will make an HTTP request to the server. Call the getUsers method inside the initState method.

@override
void initState() {
  super.initState();
  this.getUsers();
}

 

Make a Listview with API data

new ListView.builder(
    itemCount: users == null ? 0 : users.length,
    itemBuilder: (BuildContext context, int index) {
      
      var name = users[index]['name'];
      var email = users[index]['email'];

      return new Column(
        children: <Widget>[
          new ListTile(
            leading: CircleAvatar(
              child: new Icon(Icons.account_box),
            ),
            title: Text(name),
            subtitle: Text(email),
          ),
          new Divider(),
        ],
      );
})

 

App preview

rest-api-flutter.png

 

Here is full code for work with REST API and bind data to a listview with a loading indicator.

import 'package:flutter/material.dart';
import 'dart:async' show Future;
import 'dart:convert';
import 'package:http/http.dart' as http;


void main() {
  runApp(new MaterialApp(
    home: new HomePage(),
  ));
}

class HomePage extends StatefulWidget {
  @override
  HomePageState createState() => new HomePageState();
}

class HomePageState extends State<HomePage> {
  List users;
  bool loading = false;

  Future<String> getUsers() async {
    setState(() => this.loading = true);
    var response =
        await http.get('https://jsonplaceholder.typicode.com/users');

    setState(() => users = json.decode(response.body.toString()));

    setState(() => this.loading = false);
    return 'success';
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  void initState() {
    super.initState();
    this.getUsers();
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: AppBar(
        title: Text('REST API'),
      ),
      body: new Column(
        children: <Widget>[
          this.loading
              ? new Center(
                  child: new CircularProgressIndicator(),
                  heightFactor: 12.0,
                )
              : new Expanded(
                  child: new ListView.builder(
                      itemCount: users == null ? 0 : users.length,
                      itemBuilder: (BuildContext context, int index) {
                        var name = users[index]['name'];
                        var email = users[index]['email'];

                        return new Column(
                          children: <Widget>[
                            new ListTile(
                              leading: CircleAvatar(
                                child: new Icon(Icons.account_box),
                              ),
                              title: Text(name),
                              subtitle: Text(email),
                            ),
                            new Divider(),
                          ],
                        );
                      }),
                ),
        ],
      ),
    );
  }
} 

If you find this tutorial post helpful. Please share with others.


Share on


Related Post


Flutter method channel tutorial

Flutter native splash screen without plugin!

Flutter plugin development - Step by step

Duplicate GlobalKey detected - [Solved]

Flutter async validation tutorial

Flutter JSON to model converter online