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

Flutter Create a bottom tab in flutter

How to create bottom tab bar in flutter ?

January 9, 2022January 15, 2022

In this tutorial i will show you to create bottom tab in flutter. Now days bottom tabbing is much popular then creating drawer because tabbing is much easy to user and you can easily switch between the tabs. I will show you in this article to change the color of…

Read More
Uncategorized call api in angular

How to call api in angular 12?

September 10, 2021November 7, 2023

In this tutorial, we are going to call the rest API’s using the angular HttpClient. To fetch data from server we need to call api in angular so we can get the updated data from serve. Angular has vast features and library to call the web or rest API’s. Step…

Read More
Laravel Call Controller Method from Another Controller in Laravel

How to Call Controller Method from Another Controller in Laravel ?

December 2, 2023March 16, 2024

In this article we will learn Call Controller Method from Another Controller in Laravel. Sometimes we need to access the controller method from another controller to save the same code on multiple locations. Best way to achieve it is using create a separate service class or trait in PHP so…

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

  • 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 Resilience of Nature: How Forests Recover After Fires
  • Understanding Laravel Cookie Consent for GDPR Compliance
  • Understanding High Vulnerabilities: A Critical Overview of the Week of May 12, 2025
  • Installing a LAMP Stack on Ubuntu: A Comprehensive Guide
  • Understanding High Vulnerabilities: A Deep Dive into Recent Security Concerns
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version