簡體   English   中英

如何從 api 調用中獲取多個數據並綁定到 flutter 小部件

[英]How to fetch multiple data from api call and bind to a flutter widget

我真的很高興能回答我的問題。 我真的不知道如何在 flutter 的小部件中顯示所有獲取的數據,我只得到一個數據。

這就是我的 Api 響應的樣子

{
"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"
    }
]
}

這是生成的 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;
  }
}

這是我的 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'});
    }
  }
}

這是我的觀點,我只顯示一個數據

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()),
            ),
          ],
        ),
      ),
    );
  }
}

所以我的問題是如何顯示我的回復中的所有數據?

您可以使用 ListView 或 GridView。 如果除了提供給它的數據之外,您將顯示的小部件對於所有實例都是相同的,請使用 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM