Flutter Rest API Example

Flutter provides very easy way to handle or Call Rest API from URL. There is a package/plugin for that is http, you have to include this dependencies in your pubspec.yaml file, like this :

http: ^0.12.0+4

Now, you have to include this package :

import 'package:http/http.dart' as http;

Now, To use GET request, just write this one :

var response = await http.get("API_URL");
var responseBody = response.body;

To use Post request, just write this one :

var response = await http.post('API_URL', body: body);
var responseBody = response.body;

To get StatusCode of response Data use this line :

var response = await http.post('API_URL', body: body);
var responseCode = response.statusCode;

This is the full Example Code :

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class CityListPage extends StatefulWidget {
  _CityListPageState createState() => _CityListPageState();
class _CityListPageState extends State<CityListPage> {
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Select City"),
      body: FutureBuilder(
          future: getCityAPI(),
          builder: (builder, snapshot) {
            return snapshot.connectionState == ConnectionState.done
                ? snapshot.hasData
                    ? snapshot.data.length != 0
                        ? ListView.builder(
                            itemCount: snapshot.data.length,
                            itemBuilder: (builder, index) {
                              var data = snapshot.data[index];
                              return ListTile(
                                onTap: () => Navigator.of(context)
                                        arguments: data['id'])
                                    .then((value) {
                                  Navigator.pop(context, value);
                                title: Text(data['title']),
                        : Center(child: Text("No Data Found"))
                    : InkWell(
                        child: Padding(
                          padding: const EdgeInsets.all(32.0),
                          child: Text("Something Wrong, Tap to retry !"),
                        onTap: () => setState(() {}))
                : Center(child: CircularProgressIndicator());
  Future<dynamic> getCityAPI() async {
    var response = await http.get('CITY_API_URL');
    return jsonDecode(response.body);

Output of the program is :

Flutter JSON Parsing Example

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *