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

Uncategorized Laravel database transactions

How to use database transaction in laravel eloquent with example ?

January 1, 2022February 22, 2024

Database Laravel Transaction in laravel eloquent are used to execute multiple or single database operations which maintainer ACID(atomicity, consistency, isolation, and durability) property of transactions. In laravel we can archive the database transaction by DB facade. Laravel DB facade provides two methods to handle the transactions one through DB::transaction() method…

Read More
Angular How to use moment js in angular

How to use moment js in angular ?

October 13, 2022March 16, 2024

This post covers how to use Moment.js in Angular. We’ll go over why Moment.js is useful, how to install it, and how to use it in Angular to manipulate dates and times. Moment.js is a powerful and flexible library for manipulating dates and times in JavaScript. It has been around…

Read More
Dart flutter refresh page on back

How to refresh a page or widget on navigation pop/back in flutter ?

April 28, 2022November 5, 2023

Sometime in out application we want to refresh a page or widget on navigation pop/back in flutter because we want to update the state of our page so users can see the latest update based on their actions. So In this article I will show you to flutter refresh page…

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

  • 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

  • Understanding High Vulnerabilities: A Deep Dive into Recent Security Concerns
  • Understanding High Vulnerabilities in Software: A Week of Insights
  • Blocking Spam Requests with LaraGuard IP: A Comprehensive Guide
  • Enhancing API Development with Laravel API Kit
  • Exploring the Future of Web Development: Insights from Milana Cap
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version