Displaying API Data from the Internet in Flutter

Displaying API Data from the Internet in Flutter

Hello everyone, welcome back at porkaone. On this occasion we will learn how to retrieve and display data from the internet in Flutter. If you're curious, let's read in full below.

In our tutorial this time we will learn several things in flutter

1. Some basic widgets
2. Use the Http Package to retrieve data from the internet
3. Using Future Builder
4. Using GridView Builder
5. Using models

And to see the final results, you can immediately scroll to the bottom of this page.

How to Fetch and Display Data in Flutter

1. First, create a new flutter project by pressing CTRL + SHIFT + P simultaneously. Then select new project → Application → select the project storage location → then fill in the project name.

2. Create a new file in the lib folder with the name product.dart. Then copy the script below.

class Product { final int id; final String title; final double price; final double discountPercentage; final double rating; final int stock; final String brand; final String category; final String thumbnail; Product({ required this.id, required this.title, required this.price, required this.discountPercentage, required this.rating, required this.stock, required this.brand, required this.category, required this.thumbnail, }); factory Product.fromJson(Map<String, dynamic> json) { return Product( id: json['id'], title: json['title'], price: json['price'].toDouble(), discountPercentage: json['discountPercentage'].toDouble(), rating: json['rating'].toDouble(), stock: json['stock'], brand: json['brand'], category: json['category'], thumbnail: json['thumbnail'], ); } }

3. Open the main.dart file in the lib folder then replace it with the script below. I have included an explanation in the script

import 'package:flutter/material.dart'; import 'dart:convert'; import 'package:http/http.dart' as http; import 'product.dart'; void main() { runApp(MaterialApp( home: MyApp(), )); } class MyApp extends StatelessWidget { Future<List<Product>> fetchProducts() async { final response = await http.get(Uri.parse('https://dummyjson.com/products')); // Make an HTTP GET request to the given URL if (response.statusCode == 200) { // Check whether the response was successful with status code 200 (OK) final List<dynamic> productsJson = json.decode(response.body)['products']; // Gets a JSON array from the response body and converts it to a list of Product objects return productsJson.map((json) => Product.fromJson(json)).toList(); } else { // If the response is unsuccessful, throw an Exception with an error message throw Exception('Failed to load products'); } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Product Page'), ), body: FutureBuilder<List<Product>>( future: fetchProducts(), builder: (context, snapshot) { // Check snapshot status if (snapshot.hasData) { // If data is available, we get a list of products from the snapshot final List<Product> products = snapshot.data!; // Build a GridView to display products return GridView.builder( gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 2, childAspectRatio: 0.6, ), itemCount: products.length, itemBuilder: (context, index) { // Get the product at the specified index final product = products[index]; // Returns a Card widget containing product information return Card( child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ // show product thumbnail with Image.network Container( height: 150, width: MediaQuery.of(context).size.width, child: Image.network( product.thumbnail, fit: BoxFit.cover, ), ), // show data like title, category, brand, price, and rating Padding( padding: const EdgeInsets.all(8.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( product.title, style: TextStyle( fontSize: 16, fontWeight: FontWeight.bold, ), ), SizedBox(height: 4), Text( product.category, style: TextStyle( fontSize: 8, fontWeight: FontWeight.bold, ), ), SizedBox(height: 4), Text( product.brand, style: TextStyle( fontSize: 8, fontWeight: FontWeight.bold, ), ), SizedBox(height: 4), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( '\$${product.price.toStringAsFixed(2)}', style: TextStyle( fontSize: 14, fontWeight: FontWeight.bold, color: Colors.green, ), ), Text( 'Rating: '+product.rating.toStringAsFixed(2), style: TextStyle( fontSize: 10, fontWeight: FontWeight.bold, ), ), ], ), ], ), ), ], ), ); }, ); } else if (snapshot.hasError) { // If an error occurs, displays an error message in the center of the screen return Center( child: Text("${snapshot.error}"), ); } // If it is still in the process of loading data, display the loading indicator in the middle of the screen return Center( child: CircularProgressIndicator(), ); }, ), ); } }

Ok, now run your project in the emulator. If successful, the display will look like the image below. There are images, product titles, product categories, brands, prices and product ratings.

Final Result

Now you have learned several functions, packages and features in Flutter. You can develop this exercise further so that your flutter application is better. You can add an MVC model or use state management. Also read several articles related to flutter that I have prepared below.

Read Another Article ✨
📰 1. How to Display a Website in Flutter with Webview  read more
📰 2. How to Make a Bubble Bottom Bar in Flutter read more
📰 3. How to Install Java Development Kit and Add Variable Path to ENV read more
📰 4. How to Make Copy Feature in Flutter Apps read more

That's it for our flutter tutorial this time about how to display data from the internet in flutter. Hopefully this article is useful. If you have any questions, please ask directly in the comments column below. That's all and receive a salary.

Post a Comment