Home > other >  How to fetch multiple data from api call and bind to a flutter widget
How to fetch multiple data from api call and bind to a flutter widget

Time:12-28

I will really be happy for my question to be answered. i don't really know how to display all fetched data in a widget in flutter, i am only getting a single data.

This is how my Api response looks like

{
"cartItems": [
    {
        "product": {
            "_id": "61b0a14b4ce2a01b914ab953",
            "name": "Total1",
            "size": "1kg",
            "price": 700,
            "isLPG": true
        },
        "vendor": "61a72ffd8eab8af9af4cc2e7",
        "vendorName": "Total Energies",
        "vendorLogo": "/public/8-_5NKVjs-total-logo2.png",
        "quantity": 2,
        "price": 1400,
        "type": "Refil",
        "_id": "61c99030eebcb51e0f2a9a37"
    },
    {
        "product": {
            "_id": "61b0a18c4ce2a01b914ab959",
            "name": "Total3",
            "size": "3kg",
            "price": 1800,
            "isLPG": true
        },
        "vendor": "61a72ffd8eab8af9af4cc2e7",
        "vendorName": "Total Energies",
        "vendorLogo": "/public/8-_5NKVjs-total-logo2.png",
        "quantity": 1,
        "price": 1800,
        "type": "Refil",
        "_id": "61c9903feebcb51e0f2a9a3d"
    },
    {
        "product": {
            "_id": "61aa6cb89b2046e5116fabc4",
            "name": "NNPC",
            "size": "15kg",
            "price": 17000,
            "isLPG": true
        },
        "vendor": "61bde0f39dfb5060de241d24",
        "vendorName": "NNPC NG",
        "vendorLogo": "/public/o7452L7tJ-nnpc-logo.png",
        "quantity": 3,
        "price": 51000,
        "type": "Refil",
        "_id": "61c99067eebcb51e0f2a9a51"
    }
]
}

This is the generated model

class GetCartItems {
  List<CartItems>? cartItems;

  GetCartItems({this.cartItems});

  GetCartItems.fromJson(Map<String, dynamic> json) {
    if (json['cartItems'] != null) {
      cartItems = <CartItems>[];
      json['cartItems'].forEach((v) {
        cartItems!.add(new CartItems.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    if (this.cartItems != null) {
      data['cartItems'] = this.cartItems!.map((v) => v.toJson()).toList();
    }
    return data;
  }
}

class CartItems {
  Product? product;
  String? vendor;
  String? vendorName;
  String? vendorLogo;
  int? quantity;
  int? price;
  String? type;
  String? sId;

  CartItems(
      {this.product,
      this.vendor,
      this.vendorName,
      this.vendorLogo,
      this.quantity,
      this.price,
      this.type,
      this.sId});

  CartItems.fromJson(Map<String, dynamic> json) {
    product =
        json['product'] != null ? new Product.fromJson(json['product']) : null;
    vendor = json['vendor'];
    vendorName = json['vendorName'];
    vendorLogo = json['vendorLogo'];
    quantity = json['quantity'];
    price = json['price'];
    type = json['type'];
    sId = json['_id'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    if (this.product != null) {
      data['product'] = this.product!.toJson();
    }
    data['vendor'] = this.vendor;
    data['vendorName'] = this.vendorName;
    data['vendorLogo'] = this.vendorLogo;
    data['quantity'] = this.quantity;
    data['price'] = this.price;
    data['type'] = this.type;
    data['_id'] = this.sId;
    return data;
  }
}

class Product {
  String? sId;
  String? name;
  String? size;
  int? price;
  bool? isLPG;

  Product({this.sId, this.name, this.size, this.price, this.isLPG});

  Product.fromJson(Map<String, dynamic> json) {
    sId = json['_id'];
    name = json['name'];
    size = json['size'];
    price = json['price'];
    isLPG = json['isLPG'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['_id'] = this.sId;
    data['name'] = this.name;
    data['size'] = this.size;
    data['price'] = this.price;
    data['isLPG'] = this.isLPG;
    return data;
  }
}

This is my controller class

class GCP extends GetxController {
  var log = Logger();
  FlutterSecureStorage storage = FlutterSecureStorage();
  var getCartItems = GetCartItems();

  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();
    getCartItems2();
  }

  void getCartItems2() async {
    try {
      String? token = await storage.read(key: "token");
      String postURL = NetworkHandler().baseurl   ApiUtil.getCartItems;
      Map<String, String> headers = {
        "Authorization": "Bearer $token",
        'Content-Type': 'application/json;charset=UTF-8',
        'Charset': 'utf-8'
      };
      var response = await http.get(Uri.parse(postURL), headers: headers);
      if (response.statusCode == 200) {
        var body = jsonDecode(response.body);
        getCartItems = GetCartItems.fromJson(body);
        update();
      } else {
        print('Something went wrong');
      }
    } catch (ex) {
      print({ex, 'An error occured, cannot get cart items'});
    }
  }
}

This is my view, where i am displaying just a single data

import 'package:flutter/material.dart';
import 'package:gasapp_customer/src/controllers/GetCartPostController.dart';
import 'package:get/get.dart';

class GetCart extends StatelessWidget {
  final gcp = Get.put(GCP());
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Center(
              child:
                  Text(gcp.getCartItems.cartItems![0].product!.name.toString()),
            ),
          ],
        ),
      ),
    );
  }
}

So my question is how can i display all the data from my response?

CodePudding user response:

You can use ListView or GridView. If the widget that you will show will be same for all instances except the data provided to it, use GridView.builder. for more info on ListView and GridView, go to: https://api.flutter.dev/flutter/widgets/GridView-class.html https://api.flutter.dev/flutter/widgets/ListView-class.html

  • Related