无法访问提供商提供的数据

时间:2020-03-30 20:41:45

标签: flutter dart

我希望打印所选项目的数量,但无法打印。我正在使用提供程序来访问数据,但是它显示了一些错误。当我将其应用于其他地方时,相同的方法也有效,但是在这里似乎不起作用,请帮助。

我收到的数据类型的摘录:

{
    "delivery_status": true,
    "coupon_code": null,
    "cart": [
        {
            "food_item_id": "2c7289c1-17fb-4f3a-90af-7a014e051c53",
            "name": "Grape",
            "price": 35.0,
            "category": "Fresh Fruit Juice",
            "available": true,
            "veg": false,
            "egg": false,
            "restaurant": "9adafbd7-a9ba-4890-b707-c9d619c72f02",
            "quantity": 1
        },
        {
            "food_item_id": "be303557-90ce-4f9c-a30f-5a6d650977b6",
            "name": "Mix Juice",
            "price": 35.0,
            "category": "Fresh Fruit Juice",
            "available": true,
            "veg": false,
            "egg": false,
            "restaurant": "9adafbd7-a9ba-4890-b707-c9d619c72f02",
            "quantity": 2
        },
        {
            "food_item_id": "13fb9de8-c774-4f6d-af66-74cc6dedbf14",
            "name": "Boondi Raita",
            "price": 110.0,
            "category": "Salad Bar",
            "available": true,
            "veg": false,
            "egg": false,
            "restaurant": "9adafbd7-a9ba-4890-b707-c9d619c72f02",
            "quantity": 1
        }
    ],
    "total_amount": 215.0
}

映射逻辑代码段:

  CartItem _items = CartItem(
    couponCode: '',
    deliveryStatus: false,
    totalAmount: 0.0,
  );
  CartItem get items {
    return _items;
  }

  // ===============================Looks Here
  List<MenuItem> _cartProducts = [];
  List<MenuItem> get cartProducts {
    return [..._cartProducts];
  }

Future<void> getCart() async {
    Map<String, String> header = {
      'Content-type': 'application/json',
      'Authorization': accessToken,
    };
    try {
      final response = await http.get(apiURL + getCartURL, headers: header);
      print(response.statusCode);
      if (response.statusCode == 200) {
        final res = jsonDecode(response.body) as Map<String, dynamic>;
        if (res == null) {
          return _items;
        }
        _items = CartItem(
          deliveryStatus: res['delivery_status'],
          couponCode: res['coupon_code'],
          totalAmount: res['total_amount'],
        );
        // ===============================Looks Here
        List<MenuItem> cartStuff = [];
        res["cart"].forEach((cartData) {
          cartStuff.add(
            MenuItem(
              foodItemId: cartData['food_item_id'],
              category: cartData['category'],
              name: cartData['name'],
              isAvailable: cartData['available'],
              isEgg: cartData['egg'],
              isVeg: cartData['veg'],
              price: cartData['price'],
              restaurant: cartData['restaurant'],
              quantity: cartData['quantity'],
            ),
          );
        });
        // ===============================Looks Here
        _cartProducts = cartStuff;
        print(_cartProducts);
        notifyListeners();
      } else if (response.statusCode == 403) {
        fetchNewAToken().then((_) {
          if (accessToken != null && refreshToken != null) getCart();
          notifyListeners();
        });
      }
    } catch (e) {
      print("Error in getting the Cart");
      print(e);
    }
  }

用于显示数据的代码段

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import '../../globals/text_styles.dart';
import '../../globals/colors.dart';
import '../../providers/cart.dart';

class QuantityButton extends StatefulWidget {
//The item id received is correct so the error occurs is in accessing the data from the provider.
  final itemID;
  QuantityButton(this.itemID);

  @override
  _QuantityButtonState createState() => _QuantityButtonState();
}

class _QuantityButtonState extends State<QuantityButton> {
  @override
  Widget build(BuildContext context) {
    final cartData = Provider.of<Cart>(context);
    final cartQty =
        cartData.cartProducts.where((item) => item.foodItemId == widget.itemID);
    return Container(
      width: 100,
      height: 40,
      child: Card(
        color: primaryColor.withOpacity(0.9),
        elevation: 0,
        shape: RoundedRectangleBorder(
          side: BorderSide(color: Colors.black),
          borderRadius: BorderRadius.circular(10),
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            GestureDetector(
              onTap: () {
                cartData.deleteItems(widget.itemID);
              },
              child: Icon(
                Icons.arrow_left,
                color: Colors.white,
                size: 25,
              ),
            ),
            Spacer(),
            Container(
              child: Padding(
                padding: const EdgeInsets.all(3.0),
                child: Text(
                  // =========== Print Quantity Here ===========
                  '',
                  style: valueTextStyle,
                ),
              ),
            ),
            Spacer(),
            GestureDetector(
              onTap: () {
                cartData.addItems(widget.itemID);
              },
              child: Icon(
                Icons.arrow_right,
                color: Colors.white,
                size: 25,
              ),
            ),
          ],
        ),
      ),
    );
  }
}

0 个答案:

没有答案