Open In App

Flutter – Fetch Data From REST APIs

Last Updated : 28 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads