Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java for Android
  • Android Studio
  • Android Kotlin
  • Kotlin
  • Flutter
  • Dart
  • Android Project
  • Android Interview
Open In App
Next Article:
Implementing Rest API in Flutter
Next article icon

Implementing Rest API in Flutter

Last Updated : 09 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

Steps to Implementing Rest API Application

Step 1: Setting up the Project

Install the http dependency and add it in pubspec.yaml file 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 request 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";

Note: You need to use your own URL; we are not providing anything.


Step 3: Creating the Classes

Create a Fruit class & save as fruit.dart as shown below.

fruit.dart:

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.

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) {                                    // Placeholder for error handling                 return Icon(Icons.error);                },             ),             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:

fruitList.dart:

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 the main.dart file, as shown below:

main.dart:

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 the 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');   } } 

Next Article
Implementing Rest API in Flutter

M

manan2000gadwal
Improve
Article Tags :
  • Dart
  • Flutter
  • Android
  • Flutter
  • Flutter Class
  • Flutter-Packages
  • Flutter-HTTP
  • Flutter-Services

Similar Reads

    Flutter - Splitting App into Widgets
    Splitting an app into widgets refers to the breaking up of large widgets into smaller, more manageable widgets which can be inferred as smaller chunks of codes. The principal thing here is to understand when to split a widget into smaller ones. We are going to discuss when to split a widget and meth
    5 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 wa
    6 min read
    HTTP GET Request in Flutter
    There is no use of building a UI in Flutter until you integrate it with your backend. A GET request is used to extract useful data from your backend to use it in your application.Steps to implement HTTP GET RequestStep 1 : Create a new Flutter ApplicationCreate a new Flutter application using the co
    3 min read
    Flutter - Sending Data To The Internet
    Interacting with the Internet is crucial for most apps to function. In Flutter, sending data to the internet is one of them, and the http package is used to send the data to the internet. In this article, we will explore the same topic in detail. Steps to Implement Sending Data to the InternetStep 1
    5 min read
    Flutter - Make an HTTP POST Request
    In app development, the ability to fetch data from external sources, such as REST APIs, is a fundamental requirement. In Flutter, whether you need to send some data to the RESTful API, access a database, or then Send content from the Flutter App, Flutter provides you with the tools and packages(HTTP
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences