Menggunakan http Request

Pada modul ini kita akan membahas sedikit penggunaan http request. Masih melanjutkan modul sebelumnya, aplikasi akan menyimpan produk baru di server. Metoda yang digunakan adalah POST.

Untuk memudahkan tutorial, akan digunakan Firebase real time database. Link untuk http request dari firebase pada tutorial ini adalah https://flutter-azshop.firebaseio.com/

Perhatian: Langkah membuat Realtime Database dapat dilihat di https://skillplus.web.id/membuat-realtime-database-di-firebase/

Untuk menggunakan http request, kita perlu menambahkan package http, lihat disini https://pub.dev/packages/http

Install dengan cara menambahkan dependencies pada file pubspec.yaml.

dependencies:
  flutter:
    sdk: flutter
  provider: ^4.3.1
  http: ^0.12.2

Setelah itu kita buka file products_provider.dart, lalu ubah method addProduct dengan menambahkan prosedur untuk update data ke firebase.

Pertama kita tambahkan library yang digunakan.

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

Lalu ubah method addProduct seperti berikut. Perhatian link firebase adalah https://flutter-azshop.firebaseio.com, aturan dari firebase perlu ditambahkan nama file json untuk menyimpan data di firebase, pada contoh digunakan products.json.

void addProduct(Product prod) {
  const url = 'https://flutter-azshop.firebaseio.com/products.json';
  http
      .post(url,
          body: json.encode(
            {
              'title': prod.title,
              'desc': prod.desc,
              'imgURL': prod.imgURL,
              'price': prod.price,
              'isFav': prod.isFav
            },
          ))
      .then((resp) {
    final newProd = Product(
        id: json.decode(resp.body)['name'],
        title: prod.title,
        desc: prod.desc,
        price: prod.price,
        imgURL: prod.imgURL);
    _products.add(newProd);
    notifyListeners();
  });
}
//products_provider.dart

import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;

import './product.dart';

class ProductsProvider with ChangeNotifier {
  List<Product> _products = [
    Product(
      id: 'p1',
      title: 'Red Shirt',
      desc: 'A red shirt - it is pretty red!',
      price: 29.24,
      imgURL:
          'https://cdn.pixabay.com/photo/2020/05/07/07/25/woman-5140454_960_720.jpg',
    ),
    Product(
      id: 'p2',
      title: 'Sport Wear',
      desc: 'A good sport',
      price: 59.21,
      imgURL:
          'https://cdn.pixabay.com/photo/2017/12/17/08/01/asia-3023824_960_720.jpg',
    ),
    Product(
      id: 'p3',
      title: 'MackBook',
      desc: 'MacBook not Surface',
      price: 1000.14,
      imgURL:
          'https://cdn.pixabay.com/photo/2014/05/02/21/47/workstation-336369_960_720.jpg',
    ),
    Product(
      id: 'p4',
      title: 'Royal Enfield',
      desc: 'Born to ride..',
      price: 3049.15,
      imgURL:
          'https://cdn.pixabay.com/photo/2015/08/27/09/06/bike-909690_960_720.jpg',
    ),
  ];

  List<Product> get productsList {
    return [..._products];
  }

  List<Product> get productsFav {
    return _products.where((element) => element.isFav).toList();
  }

  Product findById(String pid) {
    return _products.firstWhere((el) => el.id == pid);
  }

  void addProduct(Product prod) {
    const url = 'https://flutter-azshop.firebaseio.com/products.json';
    http
        .post(url,
            body: json.encode(
              {
                'title': prod.title,
                'desc': prod.desc,
                'imgURL': prod.imgURL,
                'price': prod.price,
                'isFav': prod.isFav
              },
            ))
        .then((resp) {
      final newProd = Product(
          id: json.decode(resp.body)['name'],
          title: prod.title,
          desc: prod.desc,
          price: prod.price,
          imgURL: prod.imgURL);
      _products.add(newProd);
      notifyListeners();
    });
  }

  void updProduct(String id, Product updProd) {
    final idx = _products.indexWhere((prod) => prod.id == id);
    if (idx >= 0) {
      _products[idx] = updProd;
      notifyListeners();
    }
  }

  void delProduct(String id) {
    _products.removeWhere((prod) => prod.id == id);
    notifyListeners();
  }
}

Bila ke check di firebase, maka data product sudah terupdate

Sharing is caring:

2 thoughts on “Menggunakan http Request”

Leave a Comment