The Wayback Machine - https://web.archive.org/web/20240917044337/https://www.geeksforgeeks.org/implementing-rest-api-in-flutter/
Open In App

Implementing Rest API in Flutter

Last Updated : 13 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Along with building a UI in Flutter, we can also integrate it with the backend. Most applications use APIs to display user data. We will use the http package, which provides advanced methods to perform operations. REST APIs use simple HTTP calls to communicate with JSON data because:

  • It uses await & async features.
  • It provides various methods.
  • It provides class and http to perform web requests.

Let us see how a JSON file is used to fetch, delete, and update data in a Flutter app. We will create separate Dart files from main.dart for easier debugging and cleaner code in the following steps.

Step 1: Setting up the Project

Install the http dependency and add it in pubspec.yaml file in order to use API in the application.

dependencies:
http:

Step 2: Creating a Request 

This basic request uses the get method to fetch data from the specified URL in JSON format. Each request returns a Future<Response>. A Future<> is used to represent a potential value or error that will be available at some time in the future. For example, if you make a request to a server, the response will take a few seconds; this duration is represented by the Future<>. Here, we use the async and await features, which ensure that the response is handled asynchronously. This means that the code will not proceed until the response is received.

Future<List<Fruit>> fetchFruit() async {
final response = await http.get(url);
}
String url = "Your_URL";

Step 3: Creating the Classes

Create a Fruit class & saving as fruit.dart as shown below:

Dart
class Fruit {
  final int id;
  final String title;
  final String imgUrl;
  final int quantity;

  Fruit(
    this.id,
    this.title,
    this.imgUrl,
    this.quantity,
  );
  factory Fruit.fromMap(Map<String, dynamic> json) {
    return Fruit(json['id'], json['title'], json['imgUrl'], json['quantity']);
  }
  factory Fruit.fromJson(Map<String, dynamic> json) {
    return Fruit(json['id'], json['title'], json['imgUrl'], json['quantity']);
  }
}

Step 4: Create Class objects

Create the FruitItem in fruitItem.dart

Dart
import 'package:flutter/material.dart';
import 'fruit.dart';

class FruitItem extends StatelessWidget {
  FruitItem({required this.item});

  final Fruit item;

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.all(2),
      height: 140,
      child: Card(
        elevation: 5,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: <Widget>[
            Image.network(
              item.imgUrl,
              width: 200,
              errorBuilder: (context, error, stackTrace) {
                return Icon(Icons.error); // Placeholder for error handling
              },
            ),
            Expanded(
              child: Container(
                padding: EdgeInsets.all(5),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: <Widget>[
                    Text(
                      item.title,
                      style: TextStyle(fontWeight: FontWeight.bold),
                    ),
                    Text("id: ${item.id}"),
                    Text("quantity: ${item.quantity}"),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

Step 5: Create a List of fruits

Create a FruitList class in fruitList.dart as shown below:

Dart
import 'package:flutter/material.dart';
import 'fruit.dart';
import 'fruitItem.dart';

class FruitList extends StatelessWidget {
  final List<Fruit> items;

  FruitList({Key key, this.items});
  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemCount: items.length,
      itemBuilder: (context, index) {
        return FruitItem(item: items[index]);
      },
    );
  }
}

Step 6: Displaying the Responses

Display the response on the screen from main.dart file as shown below:

Dart
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:flutter/material.dart';
import 'fruit.dart';
import 'fruitItem.dart';
import 'fruitList.dart';

class MyHomePage extends StatelessWidget {
  final String title;
  final Future<List<Fruit>> products;

  MyHomePage({Key key, this.title, this.products}) : super(key: key);

  @override
  Widget build(BuildContext context) 
  {
    return Scaffold(
        appBar: AppBar(
          backgroundColor: Color(0xFF4CAF50),
          title: Text("GeeksForGeeks"),
        ),
        body: Center(
          child: FutureBuilder<List<Fruit>>(
            future: products,
            builder: (context, snapshot) {
              if (snapshot.hasError) print(snapshot.error);
              return snapshot.hasData
                  ? FruitList(items: snapshot.data)
                  : Center(child: CircularProgressIndicator());
            },
          ),
        ));
  }
}


Following is the JSON Data upon running the application:

JSON Data

Following is the UI screen of the homepage of Flutter application with decoded JSON data.

Output:

fruit app

Explanation of the above Program: 

1. This statement is used to import the package as http.

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

2. This statement is used to convert the JSON data.

import 'dart:convert';

3. The following statement is used to handle the error code. If the response status code is 200, then we can display the requested data; otherwise, we can show an error message to the user. You can use any URL that accepts a get() request and returns a response in JSON format.

final response = await http.get('url');
if (response.statusCode == 200) {
//display UI}
else {
//Show Error Message
}
}

4. Following statements are used in order to decode the JSON data and display the output in a user-friendly manner. This ensures that it only accepts and extracts JSON data as per our requirements.

List<Fruit> decodeFruit(String responseBody) {
final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();
return parsed.map<Fruit>((json) => Fruit.fromMap(json)).toList();
}

Now that the REST API is successfully implemented in the Flutter app, follow these steps to update, delete, or send data using the JSON file, similar to the steps for creating a request. Since we need to send the noteID to the API, we must update the noteID and include it in the path using ‘/\$id’ in the put(), delete(), or post() method. This is necessary to specify which note we are updating, deleting, or sending. Additionally, we need to re-fetch the notes after they are updated, deleted, or sent to display them.

1. Updating the data 

Dart
Future<Fruit> updateFruit(String title) async {
  final http.Response response = await http.put(
    'url/$id',
    headers: <String, String>{
      'Content-Type': 'application/json; charset=UTF-8',
    },
    body: jsonEncode(<String, String>{
      'title': title,
    }),
  );

  if (response.statusCode == 200) {
    return Fruit.fromJson(json.decode(response.body));
  } else {
    throw Exception('Failed to update album.');
  }
}


2. Deleting the data

Dart
Future<Fruit> deleteAlbum(int id) async {
  final http.Response response = await http.delete(
    'url/$id',
    headers: <String, String>{
      'Content-Type': 'application/json; charset=UTF-8',
    },
  );

  if (response.statusCode == 200) {
    return Fruit.fromJson(json.decode(response.body));
  } else {
    throw Exception('Failed to delete album.');
  }
}

3. Sending the data

Dart
Future<Fruit> sendFruit(
 
String title, int id, String imgUrl, int quantity) async {
     final http.Response response = await http.post(
     'url',
    headers: <String, String> {
      'Content-Type': 'application/json; charset=UTF-8',
    },
    body: jsonEncode(<String, String> {
      'title': title,
      'id': id.toString(),
      'imgUrl': imgUrl,
      'quantity': quantity.toString()
    }),
  );
  if (response.statusCode == 201) {
    return Fruit.fromJson(json.decode(response.body));
  } else {
    throw Exception('Failed to load album');
  }
}


Similar Reads

Flutter - Fetch Data From REST APIs
In this article, we know about how we can fetch the data from the API and show it on our screen dynamically. Dynamically means all the data came from the API using the internet or you can say that you need internet access to fetch the data. For this process, we have to follow some steps to make it successfully fetch the data. Step by Step Implement
5 min read
Implementing Flutter Gauge
Flutter gauge is an information perception widget written in dart language to make a modern, interactive, and animated gauge check and is utilized to make excellent portable application user interfaces utilizing Flutter. There is an alternate style of gauge in flutter. Following are the steps to follow in order to implement the Flutter Gauge in the
4 min read
Flutter - Implementing Calendar
Nowadays in most of the apps, we see Calendar in most of the apps for displaying birth dates or for any appointment application. Displaying the date in the app with the help of the Calendar view gives a better user experience. In this article, we are going to see how to implement Calendar in our Flutter App. Follow the steps to implement Calendar i
3 min read
Flutter - Implementing Pull to Refresh
The pull-to-refresh or (swipe-to-refresh) feature enables a user to pull down to fetch more data. The pull-to-refresh feature can be seen in many modern apps. The pull-to-refresh feature can be implemented in those components that are scrollable. In this article, we are going to implement this feature in Flutter. If you are not familiar with flutte
5 min read
Flutter - Implementing Swipe to Dismiss Feature
The Swipe to dismiss feature is used by us in many mobile apps. In this article, we will create a list of items and implement a swipe to dismiss in it. When we want to dismiss the content using swipe then we can do this with the help of swipe to dismiss widget in a flutter. Generally, we use this when we have a list of items and when we want to del
2 min read
Flutter - Implementing Overlay
Overlays let independent child widgets float visual elements on top of other widgets by inserting them into the overlay's Stack. This article discusses the implementation of Overlays in Flutter. To implement Overlay in Flutter we need to know about two Flutter built-in classes OverlayEntry class and the OverlayState class. OverlayEntry : Vaguely sp
8 min read
Flutter - Implementing Badges
Badges can be used for various purposes in an application. For example, showing the number of messages, number of items in the cart, etc. In this article, we will see the implementation of badges in Flutter using the badges Flutter package. Install the library: In the pubspec.yaml file, add badges library. Then run pub get to configure the dependen
5 min read
Flutter - Implementing Signing Out the User
In this article, we can learn how to Signout the user from a flutter application. This article is a continuation of the article that explains making google signIn UI and its authentication. It is recommended to check the same before moving ahead. Now we will implement the Sign out feature for the flutter application. Implementation: Follow the belo
4 min read
Is Flutter Worth Learning? Top 7 Reasons to Learn Flutter
In today's era, the usage of smartphones has increased exponentially and so has the use of mobile applications and websites. Meanwhile, considering future career prospects, learning web development and mobile app development is strongly recommended for all individuals. And when we come to mobile app development, there are two most-popular open-sour
5 min read
Flutter - Sharing Data Among Flutter Pages
In this article, we are going to find the solution for the problem statement "Import/send data from one page to another in flutter". Before going into the topic, there are some pre-requisites. Pre-requisites:Basics of dart programming language.Setting up Flutter in VS code or Setting up Flutter in Android Studio.Creating first flutter app | Hello W
4 min read
Flutter Quill - Rich Text Editor in Flutter Application
This post will explain how to integrate a rich text editor into your Flutter application so that it may enable rich text editing. There are many more things we can do with Flutter Quill, but they can get a little involved. The example below is a pretty basic demonstration of what we mean. Let's first discuss what flutter quill is and why we need it
5 min read
Flutter - Animated AlertDialog in Flutter
Animating an AlertDialog in Flutter involves using the Flutter animations framework to create custom animations for showing and hiding the dialogue. In this article, we are going to add an animation to an AlertDialog. A sample video is given below to get an idea about what we are going to do in this article. [video mp4="https://media.geeksforgeeks.
4 min read
Flutter - Different Types of Loading using Flutter EasyLoading
Flutter applications involve incorporating loading indicators to provide users with feedback during background operations. Flutter has a package for simplifying the process named flutter_easyloading package. This package easiest way to integrate loading indicators with various styles. In this article, we will implement different types of loading in
5 min read
How to Write TestCases For API Calls in Flutter?
Here we are going to a built app that calls an API and write test cases for it before we dive into it let’s go through some basic concepts. Software testing is a process in which we test code to ensure that it produces the excepted results at any given instance. Flutter tests consist of: Unit test - test for methods, functions, or classWidget test
8 min read
How to Create a ChatBot Application using ChatGPT API in Flutter?
A ChatBot is a computer program that uses Artificial Intelligence (AI) and Natural Language Processing (NLP) to understand customers' questions and give responses to them simulating human behavior. Building our own ChatBot from scratch requires us to train the Machine Learning (ML) model with rigorous amounts of text-based data, providing it with d
11 min read
Flutter - Fetching List of Data From API Through Dio
Dio is a powerful HTTP client for Dart, which supports Interceptors, Global configuration, FormData, File downloading, etc. and Dio is very easy to use. In this article, we will learn how to use Dio in Flutter to make API Calls and show data in ListView. Before heading toward its implementation. Why Use Dio For Internet calls?Dio makes networking f
3 min read
Flutter - Integrate Google Gemini API
Currently, Artificial Intelligence is blooming all around. You must have heard about the ChatGPT, Bard and now Google has come up with a very new Artificial intelligence Gemini which responds to users in a truly human-like way. You can connect Google Gemini with Flutter in a very simple and quick way. Let's learn how to do that. A sample video is g
5 min read
Basic Quiz App In Flutter API
Flutter API is an open-source software development kit for building beautiful UI which is natively compiled. Currently, it is available as a stable version for iOS and Android OS. In this app we are going to have the features or modules mentioned below: Five multiple-choice questions ( more questions can be added ).Four selectable options for each
8 min read
Implementing Edit Profile Data Functionality in Social Media Android App
This is the Part 3 of "Build a Social Media App on Android Studio" tutorial, and we are going to cover the following functionalities in this article: We are going to edit our profile data like changing name, changing the password of the user, and changing profile pic.Changing password is a very important feature because it may happen that sometimes
10 min read
Implementing Search for a Specific Blog On Home Page and Logout Functionality in Social Media Android App
This is the Part 7 of "Build a Social Media App in Android Studio" tutorial, and we are going to cover the following functionalities in this article: We are going to Search For a Blog on Home Page.If there are few blogs in our app then it is easy to search for a blog manually. But what happens when we have 1000 blogs then search for a particular bl
4 min read
Expandable Widget in Flutter
The expandable widgets do not have a fixed size, they expand on the screen according to the available areas on the screen. Due to size constraints, certain widgets can throw rendering errors, so widgets are made expandable. The one use of expandable widgets is cards that include images, texts, and to further read the text we can click "Read More" o
3 min read
Flutter - Mark as Favorite Feature
Adding to favorites is a prevalent feature in many applications. It enables the users to mark or save images, addressed, links or others stuff for easy future reference. In this article, we are going to see how to implement favorites or add to favorites feature in a flutter application. This article list two methods to do so. In the first method, w
9 min read
Flutter and Blockchain - Hello World Dapp
This tutorial will take you through the process of building your first mobile dapp - Hello World Dapp! This tutorial is meant for those with a basic knowledge of Ethereum and smart contracts, who have some knowledge of the Flutter framework but are new to mobile dapps. In this tutorial we will be covering: Setting up the development environmentCrea
9 min read
Flutter - Animation in Route Transition
Routes are simply Pages in Flutter applications. An application often needs to move from one page to another. But to make these transitions smoother, Animations can be used. These animations can be used to curve or tween the Animation object of the PageRouteBuilder class to alter the transition animation. We will discuss them in detail here. Let's
4 min read
Flutter - Building and Releasing APK using GitHub Actions
Github Actions is a Github tool that allows users to create CI/CD pipelines directly in a Github project instead of going to a third-party website. It assists us in developing, testing, and releasing our project very conveniently. In this article, we're going to build a workflow for our flutter project. We'll first build the project using the workf
3 min read
Flutter - Container Styling
In this article we will look at the most basic and simple widget in flutter Container. We will look that how can we style our container in different ways according to our need , so that we can effectively use this widget in our app . First of all we have to write some starting code for our project . Our code for the structure of our app will go lik
4 min read
Animated Text in Flutter
Animations make the UI more interactive and enhance the user experience. There is no limitation of creativity when it comes to animations or making the application more interactive. In Flutter, we got an easy way to display Animated text. In this article, we will see how we can animate texts using animated_text_kit. Types of Text Animations: Follow
3 min read
Flutter - Set Size to CircularProgressIndicator
In Flutter, we can simply wrap the CircularProgressIndicator widget as a Container widget and gives the height and width of the container that result in the increase and decrease in the size of the CircularProgressIndicator. A sample video is given below to get an idea about what we will do in this article. [video mp4="https://media.geeksforgeeks.o
3 min read
How to Add Route Polylines to Google Maps in Flutter?
Google Maps is used in many Android applications. We can use Polylines to represent routes for various destinations on Google Maps. So in this article, we are going to add Route Polylines to Google Maps in Flutter. Step By Step ImplementationStep 1: Create a New Project in Android StudioTo set up Flutter Development on Android Studio please refer t
4 min read
How to Choose the Right Architecture Pattern For Your Flutter App?
One of the key decisions you'll make when building a Flutter app is selecting the right architecture pattern. The architecture pattern determines how your app's code is organized and how its different components interact with each other. Choosing the right architecture can make it easier to build, test, and maintain your app over time. In this arti
4 min read
Article Tags :