Flutter – Fetch Data From REST APIs
Last Updated :
28 Aug, 2023
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/api2screen.dart' ;
import 'package:flutter/material.dart' ;
void main() {
runApp( const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo' ,
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true ,
),
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 {
if (response.statusCode == 200) {
List<dynamic> jsonData = json.decode(response.body);
setState(() {
products = jsonData.map((data) => Product.fromJson(data)).toList();
});
} else {
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text( 'Product List' ),
),
body: ListView.builder(
itemCount: products.length,
itemBuilder: (context, index) {
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(
children: [
AspectRatio(
aspectRatio: 1,
child: CachedNetworkImage(
imageUrl: product.image,
fit: BoxFit.cover,
),
),
ListTile(
title: Text(product.title),
subtitle: Text( '${product.price} \$' ),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.star, color: Colors.orange),
Text( '${product.rating}' ),
],
),
),
],
),
),
);
}
}
|
Output:
Share your thoughts in the comments
Please Login to comment...