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:

Share this:

  • Facebook
  • X

Related

Uncategorized Dart Flutter apiFlutterhttp

Post navigation

Previous post
Next post

Related Posts

Laravel Create database connection in laravel

How to make database connection in Laravel 8 ?

December 14, 2021December 14, 2021

Laravel comes with first party support for several database drivers. Laravel gives much better flexibility in terms of using the RDBMS based databases. Laravel supports MySQL, PostgreSQL, SQLite and SQL Server by default but if you want to make connection with Mongo or other database then you need to install…

Share this:

  • Facebook
  • X
Read More
Dart How to create a scroll like tiktok in flutter

How to create a scroll like tiktok in flutter ?

January 8, 2022January 15, 2022

Flutter such a great framework to develop the mobile application using flutter we can create any type of complex using with ease. In this tutorial i will show you how can we make a UI like tiktok, Reels, moj like scroll in flutter. We will use PageView to create the…

Share this:

  • Facebook
  • X
Read More
Dart How to Subscribe for Flutter NavigatorRouter Events

How to Subscribe for Flutter Navigator/Router Events ?

April 29, 2022September 11, 2022

Navigator is used to navigate between the pages and sometimes we want to subscribe for flutter Navigator/Router Events to update the widget state or to perform the specific task during the push and pop of page. Flutter provider RouteObserver mixin to subscribe the events of navigator by which we can…

Share this:

  • Facebook
  • X
Read More

Leave a ReplyCancel reply

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 9
  • Mysql
  • Php
  • Softwares
  • Ubuntu
  • Uncategorized

Archives

  • 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

  • How to Call Controller Method from Another Controller in Laravel ?
  • How to Get Domain Name in Laravel ?
  • How to Append Query String to Route in Laravel ?
  • How to Append URL Query Params to Pagination Laravel ?
  • How to Get Today Records in Laravel ?
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version