Flutter Accessing REST API - consume data with Http Get and Http Post  

Last updated Oct 28, 2020

Intergrate REST API in Flutter given a package called http to consume data from the internet.

To use  http we need to add http package in pubspec.yaml file.

This call will have other properties like await and async features while fetching the data.

 

Simple Http Request call

print(await http.read('https://flutter.dev/'));

 

Http Properties

  • read − Request the specified URL by GET method and return back the response as Future

  • get − Request the specified URL by GET method and return back the response as Future. The response is a class holding the response information.

  • post − Request the specified URL by POST method by posting the supplied data and return back the response as Future

  • put − Request the specified URL by PUT method and return back the response as Future

  • head − Request the specified URL by HEAD method and return back the response as Future

  • delete − Request the specified URL by DELETE method and return back the response as Future

 

 

Read Rest API integration in Flutter

 

 

Create HTTP Client object

Http package contains other class called Http Client 

var client = new http.Client(); 
try { 
   print(await client.get('https://flutter.dev/')); 
} 
finally { 
   client.close(); 
}

 

 

Let's Work with HTTP Requests with Flutter

 

Create a Flutter New Application

Add dependencies in pubspec.yaml file

dependencies:
  flutter:
    sdk: flutter

  http: 

 

This is an official Flutter plugin published by dart.dev

 

Now import packages in main.dart file

import 'dart:async'; 
import 'dart:convert'; 
import 'package:http/http.dart' as http;

 

Now i have an API called https://www.rrtutors.com/uploads/myproducts.json 

which will return a list of products in the below format

 


   { 
      "name": "iPhone", 
      "description": "iPhone is the stylist phone ever", 
      "price": 1000, 
      "image": "https://upload.wikimedia.org/wikipedia/commons/b/b1/IPhone_%26_iPhone_3G_fronts.jpg" 
   }, 
   { 
      "name": "Pixel", 
      "description": "Pixel is the most feature phone ever", 
      "price": 800, 
      "image": "https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcTva9ZpxoTbY8dfRYhh6ZXJvPQTKnbq0xDVxA&usqp=CAU"
   }, 
   { 
      "name": "Laptop", 
      "description": "Laptop is most productive development tool", 
      "price": 2000, 
      "image": "https://5.imimg.com/data5/BC/QD/XI/SELLER-26984831/hp-laptop-500x500.jpg" 
   }, 
   { 
      "name": "Tablet", 
      "description": "Tablet is the most useful device ever for meeting", 
      "price": 1500, 
      "image": "https://upload.wikimedia.org/wikipedia/commons/thumb/0/01/Kindle_Fire_web_browser_05_2012_1430.JPG/250px-Kindle_Fire_web_browser_05_2012_1430.JPG" 
   }, 
   { 
      "name": "Pendrive", 
      "description": "Pendrive is useful storage medium", 
      "price": 100, 
      "image": "https://cdn.pixabay.com/photo/2015/07/20/19/50/usb-853230_1280.png" 
   }
]

 

 

Now create a file called product.dart and add the below code

class Product {
   final String name; 
   final String description;
   final int price;
   final String image; 
   
   Product(this.name, this.description, this.price, this.image); 
   factory Product.fromMap(Map<String, dynamic> json) { 
      return Product( 
         json['name'], 
         json['description'], 
         json['price'], 
         json['image'], 
      );
   }
}

 

This class contains Product with all its information like name, price, description, image.

 

Now create a class called service_http.dart and add the below code to fetch the data from the API

 

import 'dart:convert';
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:rest_app/product.dart';

class HttpService {
  final String postsURL = "https://www.rrtutors.com/uploads/myproducts.json";


  List<Product> parseProducts(String responseBody) {
    final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();
    return parsed.map<Product>((json) => Product.fromJson(json)).toList();
  }

  Future<List<Product>> fetchProducts() async {
    final response = await http.get(postsURL);
    if (response.statusCode == 200) {
      return parseProducts(response.body);
    } else {
      throw Exception('Unable to fetch products from the REST API');
    }
  }
}


 

 

  • The future is used to lazy load product information. Lazy loading is a concept to defer the execution of the code until it is necessary.

  • http.get is used to fetch the data from the Internet.

  • json.decode is used to decode the JSON data into the Dart Map object. Once JSON data is decoded

 

 

Displaying Products

 

class ProductPage extends StatelessWidget {
  final HttpService httpService = HttpService();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("My Products"),
      ),
      body: FutureBuilder(
        future: httpService.fetchProducts(),
        builder: (BuildContext context, AsyncSnapshot<List<Product>> snapshot) {
          if (snapshot.hasData) {
            List<Product> posts = snapshot.data;
            return ListView(
              children: posts
                  .map(
                      (Product product) =>
                      Container(
                          padding: EdgeInsets.all(2), height: 140,
                          child: Card(
                            child: Row(
                                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                                children: <Widget>[

                                  Card(child: Image.network( product.image, width:120)),
                                  Expanded(
                                      child: Container(
                                          padding: EdgeInsets.all(5),
                                          child: Column(
                                            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                                            children: <Widget>[
                                              Text(product.name, style:TextStyle(fontWeight: FontWeight.bold)),
                                              Text(product.description),
                                              Text("Price: " + product.price.toString()),
                                              RatingBox(),
                                            ],
                                          )
                                      )
                                  )
                                ]
                            ),
                          )
                      )

              )
                  .toList(),
            );
          } else {
            return Center(child: CircularProgressIndicator());
          }
        },
      ),
    );
  }
}

 

 

Rating widget

class RatingBox extends StatefulWidget {
  @override
  _RatingBoxState createState() =>_RatingBoxState();
}
class _RatingBoxState extends State<RatingBox> {
  int _rating = 0;
  void _setRatingAsOne() {
    setState(() {
      _rating = 1;
    });
  }
  void _setRatingAsTwo() {
    setState(() {
      _rating = 2;
    });
  }
  void _setRatingAsThree() {
    setState(() {
      _rating = 3;
    });
  }
  Widget build(BuildContext context) {
    double _size = 20;
    print(_rating);
    return Row(
      mainAxisAlignment: MainAxisAlignment.end,
      crossAxisAlignment: CrossAxisAlignment.end,
      mainAxisSize: MainAxisSize.max,

      children: <Widget>[
        Container(
          padding: EdgeInsets.all(0),
          child: IconButton(
            icon: (
                _rating >= 1
                    ? Icon(Icons.star, size: _size,)
                    : Icon(Icons.star_border, size: _size,)
            ),
            color: Colors.red[500], onPressed: _setRatingAsOne, iconSize: _size,
          ),
        ),
        Container(
          padding: EdgeInsets.all(0),
          child: IconButton(
            icon: (
                _rating >= 2
                    ? Icon(Icons.star, size: _size,)
                    : Icon(Icons.star_border, size: _size, )
            ),
            color: Colors.red[500],
            onPressed: _setRatingAsTwo,
            iconSize: _size,
          ),
        ),
        Container(
          padding: EdgeInsets.all(0),
          child: IconButton(
            icon: (
                _rating >= 3 ?
                Icon(Icons.star, size: _size,)
                    : Icon(Icons.star_border, size: _size,)
            ),
            color: Colors.red[500],
            onPressed: _setRatingAsThree,
            iconSize: _size,
          ),
        ),
      ],
    );
  }
}

 

 

Now run the application it will show below output

 

Flutter Http Get

 

 

Flutter Dashboard Using SQFLite Database

 

Tags: Flutter HTTP, Flutter Htto Cllient, Http get

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

2938 Views