Flutter - Fetch Data From REST APIs
Last Updated :
24 Apr, 2025
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 Implementation
Step 1:
Firstly we have to give internet access in our app just because data came dynamically for this we have to go on pub.dev (which is the official site for the flutter package, all the flutter packages you will get here.) and there we have to search the http and then follow the instruction and import the package in our.
http: ^1.1.0
Paste it in your pubsec.yml file under the dependecies. And here we go to the next step.
Step 2:
Now You have to make the four folders in your lib folder the folder name according to you but we suggest making it meaningful, Here I created the four folders which name is apiservices, apimodel, utils, screens.
- apiservices: In this folder, we keep all the code related to the API to perform any action throw API so you can find the code here.
- apimodel: In this folder, we keep the model of the API which model we generate online and paste into our app.
- utils: Here we keep the widget of our app.
- screens: In this folder, we create our screen which we have to show in our app and on that screen we fetch the data from the API.
By this sequence, you just follow the steps and copy the code and paste it into your app and change the API link with your link and you will get your data.
main.dart
Dart
//import 'package:api/screens/api1screen.dart';
import 'package:api/screens/api2screen.dart';
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// TRY THIS: Try running your application with "flutter run". You'll see
// the application has a blue toolbar. Then, without quitting the app,
// try changing the seedColor in the colorScheme below to Colors.green
// and then invoke "hot reload" (save your changes or press the "hot
// reload" button in a Flutter-supported IDE, or press "r" if you used
// the command line to start the app).
//
// Notice that the counter didn't reset back to zero; the application
// state is not lost during the reload. To reset the state, use hot
// restart instead.
//
// This works for code too, not just values: Most code changes can be
// tested with just a hot reload.
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
//home: ProductsScreen(),
home: ProductListScreen(),
);
}
}
Just copy the code and replace your main code with it.
Model:
Make the api2model.dart file in your model folder and paste this code into your file.
Dart
class Product {
final int id;
final String title;
final double price;
final String description;
final String category;
final String image;
final double rating;
Product({
required this.id,
required this.title,
required this.price,
required this.description,
required this.category,
required this.image,
required this.rating,
});
factory Product.fromJson(Map<String, dynamic> json) {
return Product(
id: json['id'],
title: json['title'],
price: json['price'].toDouble(),
description: json['description'],
category: json['category'],
image: json['image'],
rating: json['rating']['rate'].toDouble(),
);
}
}
This model is generated online but you can create your own.
Screens:
In this folder create the api2screen.dart in your folder and copy the below the code and paste it in your file.
Dart
import 'dart:convert';
import 'package:api/utils/api2cardscreen.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import '../model/api2model.dart';
class ProductListScreen extends StatefulWidget {
@override
_ProductListScreenState createState() => _ProductListScreenState();
}
class _ProductListScreenState extends State<ProductListScreen> {
List<Product> products = [];
@override
void initState() {
super.initState();
fetchProducts();
}
Future<void> fetchProducts() async {
// you can replace your api link with this link
final response = await http.get(Uri.parse('https://fakestoreapi.com/products'));
if (response.statusCode == 200) {
List<dynamic> jsonData = json.decode(response.body);
setState(() {
products = jsonData.map((data) => Product.fromJson(data)).toList();
});
} else {
// Handle error if needed
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Product List'),
),
body: ListView.builder(
// this give th length of item
itemCount: products.length,
itemBuilder: (context, index) {
// here we card the card widget
// which is in utils folder
return ProductCard(product: products[index]);
},
),
);
}
}
Utils:
In this folder, you just create an api2cardscreen.dart and paste the code into that file.
Dart
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import '../model/api2model.dart';
class ProductCard extends StatelessWidget {
final Product product;
ProductCard({required this.product});
@override
Widget build(BuildContext context) {
return Card(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column( // this is the coloumn
children: [
AspectRatio(
aspectRatio: 1, // this is the ratio
child: CachedNetworkImage( // this is to fetch the image
imageUrl: product.image,
fit: BoxFit.cover,
),
),
ListTile(
title: Text(product.title),
subtitle: Text('${product.price} \$'), // this is fetch the price from the api
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.star, color: Colors.orange),// this will give the rating
Text('${product.rating}'),
],
),
),
],
),
),
);
}
}
Output:
Similar Reads
Flutter - Fetching Data From the Internet
In today's world, most applications heavily rely on fetching information from the servers through the internet. In Flutter, such services are provided by the http package. In this article, we will explore this concept.Steps to Implement Data Fetching from the InternetStep 1 : Create a new flutter ap
4 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
3 min read
Flutter - Extract Data From an Image to Text
Google ML kit provides many features, one of them is Image to Text Extraction, through which we can simply extract text from an image. To extract text from the image first we need to take an image as input either from the gallery or camera for which we will use 'image_picker: ^1.0.4' (dependency fro
3 min read
Flutter - Return Data from Screen
Interaction with UI is an essential part of any application. During the same, there might be a need to return data from the screen. This kind of interaction can range from selecting an option to navigating to different routes through the various buttons in the UI. In this article, we will explore th
4 min read
Flutter - Read and Write Data on Firebase
Firebase helps developers to manage their mobile apps easily. It is a service provided by Google. Firebase has various functionalities available to help developers manage and grow their mobile apps. In this article, we will learn how to write and read data into/from Firebase. Follow the 3-step proce
4 min read
Flutter - Fetching JSON Data using HTTP
In this article, we will learn how to fetch data from the internet or JSON file using the HTTP package in a flutter.What is HTTP?The HTTP is a composable, future-based library for making HTTP requests. This package contains a set of high-level functions and classes that make it easy to consume HTTP
5 min read
Flutter - Read JSON Data from Assets Folder
A JSON object contains data in the form of key/value pair. The keys are strings and the values are the JSON types. Keys and values are separated by a colon. Each entry (key/value pair) is separated by a comma. We will learn how to read the data already stored in your project folder in your app with
3 min read
Flutter Projects From Beginner to Advanced
Flutter is an open-source UI software development kit created by Google, designed for building natively compiled applications for mobile, web, and desktop from a single codebase. It uses the Dart programming language and provides a rich set of pre-designed widgets, allowing developers to create visu
4 min read
Flutter - Load Text Assets
In Flutter, you can easily load text assets such as JSON files, configuration files, or plain text files into your app's memory at runtime. This allows you to access the data contained in these files and use it to populate your app's UI or perform other operations. To load text assets in Flutter, yo
3 min read
Flutter - Pick and Open Files From Storage
Sometimes in an app, we need to pick and open a file from the phone's storage, in this article, we will achieve the same using file_picker and open_file flutter packages. 1. Create an App: Create a new flutter app by running the below command on your terminal: flutter create your_app_name Now open y
5 min read