颤振错误:在 null 上调用了方法“[]”。接收者:null 尝试调用:[]("product")

时间:2021-07-06 13:08:15

标签: flutter dart flutter-layout flutter-dependencies flutter-test

当我点击我的购物车图标然后在这个页面中打开我的 carpage.dart 时,我的数据没有显示并给出错误,但是当我使用快速重新加载颤动页面时,该数据即将到来。 如何解决,请帮帮我。

错误=> 方法 '[]' 在 null 上被调用。接收者:空尝试调用:

enter image description here

这是我的cartPage.dart

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:hospital/CartPage/components/cartCard.dart';
import 'package:hospital/CartPage/components/priceDetailsCard.dart';
import 'package:hospital/constant.dart';
import 'package:hospital/customApiVariable.dart';
import 'package:http/http.dart' as http;

class Cartpage extends StatefulWidget {
  @override
  _CartpageState createState() => _CartpageState();
}

class _CartpageState extends State<Cartpage> {
  var response;

  var addToCartApi;

  @override
  void initState() {

    super.initState();

    fetchData();
  }

  fetchData() async {
    var api = Uri.parse(
        '$ecommerceBaseUrl/addToCartApi.php?a2rTokenKey=$a2rTokenKey&action=addToCartList&uid=${var_uid}');

    response = await http.get(api);

    print("Carousel" + response.body);
    addToCartApi = jsonDecode(response.body);
    print('addToCartApi' + addToCartApi['total'].toString());


// store in variable 
    totalOfferPrice = addToCartApi['total']['grandTotalOfferPrice'].toString();
    totalPrice = addToCartApi['total']['grandTotalPrice'].toString();
    totalPriceAfterOffer =
        addToCartApi['total']['grandTotalPriceAfterOffer'].toString();
    deliveryName = addToCartApi['total']['deliveryName'];
    deliveryCharge = addToCartApi['total']['deliveryCharge'].toString();
    total_num = addToCartApi['total']['num'].toString();

    setState(() {});
  }

  // List allItems = CartRepo().getAllCartItems();
  @override
  Widget build(BuildContext context) {
    final _media = MediaQuery.of(context).size;
    return Scaffold(
        appBar: AppBar(
          backgroundColor: kGreen,
          title: Text("My Cart"),
        ),
        body: Stack(
          children: [
            Container(
              decoration: BoxDecoration(color: Color(0xFFeeeeee)),
              height: _media.height,
              width: _media.width,
            ),
            ListView(
              shrinkWrap: true,
              children: <Widget>[
                CartCard(user_id: var_uid),
                PriceDetailsCard(totalItem: addToCartApi['total']),
                SizedBox(
                  height: 100,
                )
              ],
            ),
            Align(
              alignment: Alignment.bottomCenter,
              child: Container(
                width: _media.width,
                height: _media.height * .08,
                decoration: BoxDecoration(color: Colors.white, boxShadow: [
                  BoxShadow(color: Colors.black87, blurRadius: 5.0),
                  BoxShadow(color: Colors.white, blurRadius: 10.0),
                ]),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    Padding(
                      padding: const EdgeInsets.only(left: 10.0),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: <Widget>[
                          Text(
                            "\u20B9 ${totalPriceAfterOffer}",
                            style: TextStyle(
                                fontWeight: FontWeight.bold, fontSize: 20),
                          ),
                          Text(
                            "View price details",
                            style: TextStyle(
                                color: Colors.blueGrey,
                                fontWeight: FontWeight.bold),
                          )
                        ],
                      ),
                    ),
                    Padding(
                      padding: const EdgeInsets.only(right: 10.0),
                      child: Container(
                          width: _media.width * .4,
                          child: RaisedButton(
                            onPressed: () {},
                            color: kGreen,
                            child: Text(
                              "PLACE ORDER",
                              style: TextStyle(color: Colors.white),
                            ),
                          )),
                    ),
                  ],
                ),
              ),
            )
          ],
        ));
  }
}

这是 CartCard.dart 页面

import 'dart:convert';

import 'package:flutter/material.dart';
// import 'package:hospital/FourthDelete/fourth_delete.dart';
// import 'package:hospital/FourthSection/MedicineProductList/medicine_product_list.dart';
import 'package:hospital/ProductDetailsPage/product_detailPage.dart';
import 'package:hospital/SecondSection/Medicine/medicine_page.dart';
import 'package:hospital/constant.dart';
import 'package:hospital/customApiVariable.dart';
import 'package:http/http.dart' as http;

class CartCard extends StatefulWidget {
  final user_id;

  const CartCard({Key key, this.user_id}) : super(key: key);
  @override
  _CartCardState createState() => _CartCardState();
}

class _CartCardState extends State<CartCard> {
  var response;

  //this drinks call from api
  var cartCardApi;

  @override
  void initState() {
    // TODO: implement initState
    //
    super.initState();
// for loading
    fetchData(widget.user_id);
  }

  fetchData(auth_uid) async {
    // var api = Uri.parse(
    //     'https://www.a2rstore.in/oceonicApi/ecommerce/v2/api/categoryApi.php?a2rTokenKey=carpet1234');
    // var api = Uri.parse('$baseUrl/productCatApi.php?a2rTokenKey=$a2rTokenKey');
    var api = Uri.parse(
        // '$ecommerceBaseUrl/addToCartApi.php?a2rTokenKey=$a2rTokenKey&action=addToCartList&uid=${widget.auth_uid}');
        '$ecommerceBaseUrl/addToCartApi.php?a2rTokenKey=$a2rTokenKey&action=addToCartList&uid=${widget.user_id}');
    // 'https://www.a2rstore.in/oceonicApi/ecommerce/v1/api/productSubCatApi.php?a2rTokenKey=a2rhos1234&pcat=60c461f032f2a');
    response = await http.get(
      api,
    );
    print("cartCardApi " + api.toString());
    print("cartCardbody " + response.body);

    // in double quotes drink is key value of json

    cartCardApi = jsonDecode(response.body);

    print("cartCardApi " + cartCardApi.toString());
    return cartCardApi['product'];
    // setState(() {});
  }

  String quantity = "1";
  @override
  Widget build(BuildContext context) {
    final _media = MediaQuery.of(context).size;
    return ListView.builder(
        // itemCount: categoryApi.length.clamp(0, 3),//THis is for showed minimun length of item listview.builder flutter
        itemCount: cartCardApi['product'].length,
        scrollDirection: Axis.vertical,
        physics: ScrollPhysics(),
        shrinkWrap: true,
        itemBuilder: (context, index) {
          var cartCard = cartCardApi['product'][index];
          return Container(
            height: _media.height * .4,
            child: Card(
              color: Colors.white,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Padding(
                        padding: const EdgeInsets.only(
                            left: 10.0, top: 10, bottom: 8),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            Container(
                              width: _media.width * .6,
                              child: Text(
                                // widget.item.desc,
                                cartCard["productName"],
                                maxLines: 2,
                                style: TextStyle(
                                    color: Colors.black,
                                    fontSize: 18,
                                    fontWeight: FontWeight.w500),
                                overflow: TextOverflow.ellipsis,
                              ),
                            ),
                            SizedBox(
                              height: 5,
                            ),
                            Text(
                              // widget.item.quantity,
                              ' Quantity ${cartCard['orderQuantity']}',
                              style:
                                  TextStyle(color: Colors.grey, fontSize: 14),
                            ),
                            SizedBox(
                              height: 10,
                            ),
                            Row(
                              children: <Widget>[
                                Text(
                                  "Seller: ",
                                  style: TextStyle(
                                      color: Colors.grey, fontSize: 14),
                                ),
                                Icon(
                                  Icons.check_circle,
                                  color: Colors.grey,
                                  size: 15,
                                )
                              ],
                            ),
                            SizedBox(
                              height: 15,
                            ),
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              crossAxisAlignment: CrossAxisAlignment.end,
                              children: <Widget>[
                                Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: <Widget>[
                                    Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.start,
                                      children: <Widget>[
                                        Text(
                                          "\u20B9 " +
                                              cartCard[
                                                  'productPriceAfterOffer'],
                                          style: TextStyle(
                                              fontWeight: FontWeight.bold,
                                              fontSize: 23),
                                        ),
                                        Padding(
                                          padding:
                                              const EdgeInsets.only(left: 10.0),
                                          child: Text(
                                            "\u20B9 " +
                                                cartCard['productRealPrice'],
                                            style: TextStyle(
                                                color: Colors.grey,
                                                decoration:
                                                    TextDecoration.lineThrough),
                                          ),
                                        ),
                                        SizedBox(
                                          width: 5,
                                        ),
                                        Text(
                                          '40' + "%off",
                                          style: TextStyle(
                                              color: Colors.green,
                                              fontSize: 13,
                                              fontWeight: FontWeight.w600),
                                        )
                                      ],
                                    ),
                                    SizedBox(
                                      height: 10,
                                    ),
                                    Text(
                                      "2 offers available",
                                      style: TextStyle(
                                          color: Colors.green,
                                          fontSize: 13,
                                          fontWeight: FontWeight.w600),
                                    )
                                  ],
                                )
                              ],
                            )
                          ],
                        ),
                      ),
                      Padding(
                        padding: const EdgeInsets.only(
                            top: 10.0, right: 8, bottom: 8),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            Container(
                              color: Colors.white,
                              child: Row(
                                children: <Widget>[
                                  Container(
                                    width: _media.width * .3,
                                    height: _media.height * .2,
                                    child: Image.network(
                                      // 'https://media.gettyimages.com/photos/woman-using-meal-delivery-service-through-mobile-app-picture-id1160735344?k=6&m=1160735344&s=612x612&w=0&h=tYEeckvNDyAoyUEfUeCii_29p_pBum_BVHKiUrGbjYY=',
                                      cartCard['pImgImg'],
                                      fit: BoxFit.cover,
                                    ),
                                  )
                                ],
                              ),
                            ),
                            Row(
                              children: <Widget>[
                                Text(
                                  "Qty:",
                                  style: TextStyle(fontWeight: FontWeight.bold),
                                ),
                                SizedBox(
                                  width: 10,
                                ),
                                DropdownButton<String>(
                                  value: quantity,
                                  items: <String>["1", "2", "3", "4", "5"]
                                      .map((String value) =>
                                          DropdownMenuItem<String>(
                                              value: value, child: Text(value)))
                                      .toList(),
                                  onChanged: (_value) {
                                    setState(() {
                                      quantity = _value;
                                    });
                                  },
                                )
                              ],
                            ),
                          ],
                        ),
                      )
                    ],
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      Container(
                        height: _media.height * .08,
                        width: _media.width * .4875,
                        child: RaisedButton(
                          onPressed: () {},
                          color: Colors.white,
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: <Widget>[
                              Icon(
                                Icons.favorite,
                                size: 15,
                                color: Colors.grey,
                              ),
                              SizedBox(
                                width: 5,
                              ),
                              Text(
                                "SAVE FOR LATER",
                                style: TextStyle(fontSize: 15),
                              )
                            ],
                          ),
                        ),
                      ),
                      Container(
                        height: _media.height * .08,
                        width: _media.width * .4875,
                        child: RaisedButton(
                          onPressed: () {},
                          color: Colors.white,
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: <Widget>[
                              Icon(
                                Icons.delete,
                                size: 15,
                                color: Colors.grey,
                              ),
                              SizedBox(
                                width: 5,
                              ),
                              Text(
                                "REMOVE",
                                style: TextStyle(fontSize: 15),
                              )
                            ],
                          ),
                        ),
                      ),
                    ],
                  )
                ],
              ),
            ),
          );
        });
  }
}

这是我的json数据

{
  "product": [
    {
      "plistId": "60c71ed46839f",
      "plistPriceId": "",
      "uid": "60daaedd3b9f8751161",
      "orderQuantity": "1",
      "date": "2021-07-06",
      "productName": "MUKTI CHURNA",
      "productCode": "499",
      "productlink": "detail.php?pListName=MUKTI CHURNA&plistId=60c71ed46839f",
      "productRealPrice": "1112",
      "productPriceAfterOffer": 1110,
      "productOfferAmountMulOrdrQuantity": 0,
      "quantity": "1 p",
      "pImgImg": "http:\/\/a2rstore.com\/inventory\/images\/product_images\/product-Mukti-Churan-600x600.jpg",
      "subTotalRealPrice": 1110,
      "subTotalofferPrice": 0,
      "subTotalPriceAfterOffer": 1110
    },
    {
      "plistId": "60cacee2ee4ff",
      "plistPriceId": "",
      "uid": "60daaedd3b9f8751161",
      "orderQuantity": "1",
      "date": "2021-07-06",
      "productName": " PAIN CALM OIL",
      "productCode": "504",
      "productlink": "detail.php?pListName= PAIN CALM OIL&plistId=60cacee2ee4ff",
      "productRealPrice": "123",
      "productPriceAfterOffer": "123",
      "productOfferAmountMulOrdrQuantity": 0,
      "quantity": "1 p",
      "pImgImg": "http:\/\/a2rstore.com\/inventory\/images\/product_images\/product-Oil-pulling-ff-600x600.jpg",
      "subTotalRealPrice": 123,
      "subTotalofferPrice": 0,
      "subTotalPriceAfterOffer": 123
    },
    {
      "plistId": "60cacee2ee4ff",
      "plistPriceId": "",
      "uid": "60daaedd3b9f8751161",
      "orderQuantity": "3",
      "date": "2021-07-06",
      "productName": " PAIN CALM OIL",
      "productCode": "504",
      "productlink": "detail.php?pListName= PAIN CALM OIL&plistId=60cacee2ee4ff",
      "productRealPrice": "123",
      "productPriceAfterOffer": "123",
      "productOfferAmountMulOrdrQuantity": 0,
      "quantity": "1 p",
      "pImgImg": "http:\/\/a2rstore.com\/inventory\/images\/product_images\/product-Oil-pulling-ff-600x600.jpg",
      "subTotalRealPrice": 369,
      "subTotalofferPrice": 0,
      "subTotalPriceAfterOffer": 369
    },
    {
      "plistId": "60cacee2ee4ff",
      "plistPriceId": "",
      "uid": "60daaedd3b9f8751161",
      "orderQuantity": "3",
      "date": "2021-07-06",
      "productName": " PAIN CALM OIL",
      "productCode": "504",
      "productlink": "detail.php?pListName= PAIN CALM OIL&plistId=60cacee2ee4ff",
      "productRealPrice": "123",
      "productPriceAfterOffer": "123",
      "productOfferAmountMulOrdrQuantity": 0,
      "quantity": "1 p",
      "pImgImg": "http:\/\/a2rstore.com\/inventory\/images\/product_images\/product-Oil-pulling-ff-600x600.jpg",
      "subTotalRealPrice": 369,
      "subTotalofferPrice": 0,
      "subTotalPriceAfterOffer": 369
    },
    {
      "plistId": "60cacee2ee4ff",
      "plistPriceId": "",
      "uid": "60daaedd3b9f8751161",
      "orderQuantity": "1",
      "date": "2021-07-06",
      "productName": " PAIN CALM OIL",
      "productCode": "504",
      "productlink": "detail.php?pListName= PAIN CALM OIL&plistId=60cacee2ee4ff",
      "productRealPrice": "123",
      "productPriceAfterOffer": "123",
      "productOfferAmountMulOrdrQuantity": 0,
      "quantity": "1 p",
      "pImgImg": "http:\/\/a2rstore.com\/inventory\/images\/product_images\/product-Oil-pulling-ff-600x600.jpg",
      "subTotalRealPrice": 123,
      "subTotalofferPrice": 0,
      "subTotalPriceAfterOffer": 123
    },
    {
      "plistId": "60cacee2ee4ff",
      "plistPriceId": "",
      "uid": "60daaedd3b9f8751161",
      "orderQuantity": "1",
      "date": "2021-07-06",
      "productName": " PAIN CALM OIL",
      "productCode": "504",
      "productlink": "detail.php?pListName= PAIN CALM OIL&plistId=60cacee2ee4ff",
      "productRealPrice": "123",
      "productPriceAfterOffer": "123",
      "productOfferAmountMulOrdrQuantity": 0,
      "quantity": "1 p",
      "pImgImg": "http:\/\/a2rstore.com\/inventory\/images\/product_images\/product-Oil-pulling-ff-600x600.jpg",
      "subTotalRealPrice": 123,
      "subTotalofferPrice": 0,
      "subTotalPriceAfterOffer": 123
    }
  ],
  "total": {
    "grandTotalOfferPrice": 0,
    "grandTotalPrice": 123,
    "grandTotalPriceAfterOffer": 123,
    "deliveryName": "Shipping Charge",
    "deliveryCharge": "Free",
    "num": 6
  }
}

3 个答案:

答案 0 :(得分:2)

根据错误,在您在 ListView 中访问它之前,您的 cartCardApi 为空。

如果是 API 调用,则使用 FutureBuilder 处理所有异步调用,例如显示加载、api 出错时出错,如果成功则 ui。

否则将cartCardApi 设为之前的空列表。

这样,当您调用 setState 时,新列表会更新,并且 ui 会获取新列表。

答案 1 :(得分:0)

当您尝试获取“产品”值时,您的 cartCardApi 似乎是 null

答案 2 :(得分:0)

您尝试从产品中获取数据的方式似乎是错误的。尝试从响应中打印完整的 JSON 并打印每个单独的项目以查看正确的值。

这就是为什么首选 JSON 格式的原因,您可以在其中为响应值创建模型类,并将响应值映射到模型类中的预定义键,然后使用该模型类在 UI 中填充值。

避免这些类型的错误

https://medium.com/flutter-community/parsing-complex-json-in-flutter-747c46655f51