Skip to content
Readerstacks logo Readerstacks
  • Home
  • Softwares
  • Angular
  • Php
  • Laravel
  • Flutter
Readerstacks logo
Readerstacks
Flutter http request to call api

Simple way to call API in flutter using http package

Aman Jain, January 11, 2022January 15, 2022

Every client side application require connection to server to share the data and get most updated data from server. In the same way flutter also require to call the APIs’ and get data from server and also store the data in server. So in this article i will show you to use Http Request using get and post method.

Http Request are used to communicate between client and server applications. In Flutter we use Http package.

Let’s call APIs in flutter using http package step by step

Step 1 : Create flutter project

First step is to create the fluter application using command line tool or in Android studio.

flutter create example_app

This will create a new project with name example_app then go in to the folder.

Step 2 : Add http package in application

We are going to use http request so we need to add http package first. so add http package in pubspec.yaml

name: example_app
description: A new Flutter project.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev

version: 1.0.0+1

environment:
  sdk: ">=2.15.1 <3.0.0"

dependencies:
  flutter:
    sdk: flutter
  cupertino_icons: ^1.0.2
  http: ^0.13.4

dev_dependencies:
  flutter_test:
    sdk: flutter

  flutter_lints: ^1.0.0

flutter:

  uses-material-design: true

  assets:
    - assets/images/

here we added http: ^0.13.4 in dependencies block

dependencies:
  flutter:
    sdk: flutter
  cupertino_icons: ^1.0.2
  http: ^0.13.4

Also make sure to add latest version always from https://pub.dev/packages/http.

Then run command

flutter --no-color pub get

Step 3 : Import and use http package in widget

After adding the http package now we can use it in our dart file so import the http package

File : lib/HttpDemo.dart

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

Here we imported package:http/http.dart and given an alias as http so now lets’s make a http get request and parse the JSON


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

class HttpDemo extends StatefulWidget {
  const HttpDemo({Key? key}) : super(key: key);

  @override
  _HttpDemoState createState() => _HttpDemoState();
}

class _HttpDemoState extends State<HttpDemo> {

   List jsonData=[];

  @override
  void initState() {
    super.initState();
    getJsonData();


  }
   getJsonData() async{

    final response = await http
        .get(Uri.parse('https://jsonplaceholder.typicode.com/albums'));
   
    if (response.statusCode == 200) {
      // If the server did return a 200 OK response,
      // then parse the JSON.

      setState(() {
        jsonData =  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');
    }
  }

  buildLayout(){
    if(jsonData.isEmpty) {
    return  Center(
        child: SizedBox(
          child: CircularProgressIndicator(
            backgroundColor: Theme
                .of(context)
                .primaryColor,
            strokeWidth: 2,
          ),
          height: 25.0,
          width: 25.0,
        ),
      );
    }
    else{

      return ListView(
        children: jsonData.map((e){ 
          return Container(
          margin: const EdgeInsets.all(5),
          child: "Title : "+Text(e['title']  )
          );
        }
    ).toList(),
      );
    }
  }


  @override
  Widget build(BuildContext context) {
    return  MaterialApp(
        title: 'Flutter Demo',
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),
        home: Scaffold(
        appBar: AppBar(
        title: const Text('Readerstacks Http Demo'),
    ),

    body:buildLayout()
    )
    );
  }
}

Here we used getJsonData to fetch http request and then on response setState again to rebuild the widget.

 getJsonData() async{

    final response = await http
        .get(Uri.parse('https://jsonplaceholder.typicode.com/albums'));
    
    if (response.statusCode == 200) {
      // If the server did return a 200 OK response,
      // then parse the JSON.

      setState(() {
        jsonData =  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');
    }
  }

Here we used json.decode to decode the response in List using package import ‘dart:convert’.

we also create a method buildLayout to show loading indicator until jsonData variable is empty once its filled with data then we are showing list view as below

 buildLayout(){
    if(jsonData.isEmpty) {
    return  Center(
        child: SizedBox(
          child: CircularProgressIndicator(
            backgroundColor: Theme
                .of(context)
                .primaryColor,
            strokeWidth: 2,
          ),
          height: 25.0,
          width: 25.0,
        ),
      );
    }
    else{

      return ListView(
        children: jsonData.map((e){ 
          return Container(
          margin: const EdgeInsets.all(5),
          child: "Title : "+Text(e['title']  )
          );
        }
    ).toList(),
      );
    }
  }

Step 3 : Add Page to main file

Add you new pages to main.dart and start tabbing.

import 'package:flutter/material.dart';
import 'package:example_app/HttpDemo.dart';

void main() => runApp(HttpDemo());

 

Step 4: Run the project

Simply run the project using command line or in android studio to check the implementation.

flutter run lib/main.dart

Live Preview:

Related

Uncategorized Dart Flutter apiFlutterhttp

Post navigation

Previous post
Next post

Related Posts

Dart Navigating between pages in flutter

How to navigate between one page to another in flutter ?

January 4, 2022January 15, 2022

Flutter provides its inbuilt navigator to navigate between pages. In our application it must have multiple screens and we wanted to navigate on all screens so in flutter we use Navigator class to navigate between pages. In android we use Activity and in iOS we use ViewController to navigate between…

Read More
Uncategorized update page data without reload

How to update page data without reload in jQuery?

October 24, 2021November 17, 2023

If you are beginner then this post is for you. For showing the new content on page without refresh we will use JQuery Reload Page without Refresh and server side PHP. In this article, I will demonstrate to show the latest content from server without refreshing the page. This is…

Read More
Uncategorized setup simple jQuery form validation

How to setup simple jQuery form validation?

September 15, 2021September 29, 2021

In this tutorial, we are going to learn jQuery form validation using jQuery validation plugin. this plugin have many features like to validate text, email, phone number , sync Ajax request etc. Let’s begin with step by step guide: Step 1: Create a html file Firstly we are going to…

Read More

Aman Jain
Aman Jain

With years of hands-on experience in the realm of web and mobile development, they have honed their skills in various technologies, including Laravel, PHP CodeIgniter, mobile app development, web app development, Flutter, React, JavaScript, Angular, Devops and so much more. Their proficiency extends to building robust REST APIs, AWS Code scaling, and optimization, ensuring that your applications run seamlessly on the cloud.

Categories

  • Angular
  • CSS
  • Dart
  • Devops
  • Flutter
  • HTML
  • Javascript
  • jQuery
  • Laravel
  • Laravel 10
  • Laravel 11
  • Laravel 9
  • Mysql
  • Php
  • Softwares
  • Ubuntu
  • Uncategorized

Archives

  • August 2025
  • July 2025
  • June 2025
  • May 2025
  • April 2025
  • October 2024
  • July 2024
  • February 2024
  • January 2024
  • December 2023
  • November 2023
  • October 2023
  • July 2023
  • March 2023
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • July 2022
  • June 2022
  • May 2022
  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • June 2021

Recent Posts

  • The Transformative Power of Education in the Digital Age
  • Understanding High Vulnerabilities: A Closer Look at the Week of July 14, 2025
  • Exploring Fresh Resources for Web Designers and Developers
  • The Intersection of Security and Technology: Understanding Vulnerabilities
  • Mapping Together: The Vibrant Spirit of OpenStreetMap Japan
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version